Mybatis使用详解

一、概念

是一款优秀的持久层框架,用于简化JDBC开发

持久层

  • 负责将数据保存到数据库的一层代码
  • JaveEE三层架构:表现层,业务层,持久层

二、JDBC缺点

1.硬编码

  • 注册驱动
  • 获取连接

2.操作繁琐

  • 手动设置参数
  • 手动封装结果集

三、快速入门

1.查询user表中所有的数据

(1)创建user表,添加数据
(2)创建模块,导入坐标

<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.5</version>
</dependency>
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.46</version>
</dependency>
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-api</artifactId>
  <version>1.7.20</version>
</dependency>
<dependency>
  <groupId>ch.qos.logback</groupId>
  <artifactId>logback-classic</artifactId>
  <version>1.2.3</version>
</dependency>
<dependency>
  <groupId>ch.qos.logback</groupId>
  <artifactId>logback-core</artifactId>
  <version>1.2.3</version>
</dependency>

(3)编写MyBatis核心配置文件

mybatis-config.xml

(4)编写SQL映射文件

UserMapper.xml

	namespace

		- 名称空间

	resultType

		- 返回类型

	id

		- 唯一标识

(5)编码

  • 定义POJO类

  • 加载核心配置文件,获取SqlSessionFactory对象

      String resource = "mybatis-config.xml";
      InputStream inputStream = Resources.getResourceAsStream(resource);
      SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    
  • 获取SqlSession对象,执行SQL语句

      SqlSession sqlSession = sqlSessionFactory.openSession();
      List<User> users = sqlSession.selectList("test.selectAll");
    
  • 释放资源

      - sqlSession.close();
    

四、解决映射文件警告提示

1.产生原因

  • idea和数据库没有建立连接,不识别表信息

2.解决方法

  • 在idea中配置MySql数据库连接

    • 界面右边Database->MySql

五、Mapper代理开发

1.目的

  • 解决原生方式中的硬编码
  • 简化后期执行SQL

2.入门案例步骤

  • 定义与SQL映射文件同名的Mapper接口,并将Mapper接口与SQL映射文件放置在同一目录下

  • 在resources下创建com/lee/mapper

  • 设置SQL映射文件的namespace属性为Mapper接口全限定名

      <mapper namespace="com.lee.mapper.UserMapper">
      <select id="selectAll" resultType="com.lee.pojo.User">
      select * from tb_user;
      </select>
      </mapper>
    
  • 在Mapper接口中定义方法,方法名就是SQL映射文件中sql语句的id,并保持参数类型和返回值类型一致

      public interface UserMapper {
        List<User> selectAll();
      }
    
  • mybaiis核心配置文件

       <mappers>
    
       <mapper resource="com/lee/mapper/UserMapper.xml"/>
       </mappers>
    
  • 编码

    • 通过SqlSession的getMapper方法获取Mapper接口的代理对象

        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
      
    • 调用对应方法完成sql的执行

         List<User> users = userMapper.selectAll();
      
  • 如果Mapper接口名称和SQL映射文件名称相同且在同一目录下,可以使用包扫描的方式简化SQL映射文件加载

      <mappers> 
      <package name="com.lee.mapper"/>
      </mappers>
    

六、mybatis核心配置文件

1.environment

  • 环境,可以配置不同的数据库
  • 可以配置多个数据源,通过default属性切换

2.transactionManager

  • 事务

3.类型别名(typeAliases)

 <typeAliases>
<package name="com.lee.pojo"/>
</typeAliases>
  • 扫描pojo下面所有类,可以直接resultType=“com.lee.pojo.user”

配置各个标签时,需要遵守先后顺序

七、MybatisX插件

  • 主要功能

XML和接口方法互相跳转

根据接口方法生成statement

八、别名

1.对数据库和pojo类属性不一样的起别名

  • select id , brand_name as brand_Name

2.定义sql片段

  • brand_name as brand_Name
  • select from tb_brand;

九、resultMap

 <resultMap id="brandResultMap" type="com.lee.pojo.Brand">
    <result column="brand_name" property="brandName"/>
    <result column="company_name" property="companyName"/>
</resultMap>
<select id="selectAll" resultMap="brandResultMap">
    select * from tb_brand;
</select>

1.定义标签

2.在select标签中使用resultMap属性替换resultType属性

十、查询Mapper

<select id="selectById"resultMap="brandResultMap">
    select  * from tb_brand where id = #{id};
</select>

1.参数占位符

  • #{}

    • 会将其替换为?,防止sql注入

      • 参数传递的时候
  • ${}

    • 拼sql,会存在sql注入问题

      • 表名或列名不固定的时候

2.参数类型

  • parameterType

    • 定义id数据类型

      • 可省略

3.特殊字符处理

  • 转义

    • <
  • CDATA

    • CD

4.多参数接收

@Param("status")int status

十一、动态条件查询

1.if条件语句

<if test=""></if>

 <select id="selectByCondition" resultMap="brandResultMap">
    select * from tb_brand
    where 1=1 / <where>
        <if test="status != null">
           and status = #{status}
        </if>
      <if test="companyName != null and companyName != ''">
          and company_name like #{companyName}
      </if>
      <if test="brandName != null and brandName != ''">
          and brand_name like #{brandName}
      </if>
</select>

2.choose条件语句

  • 类似于switch,从多个条件中选择一个

      <choose>
    <when test = "">
    </when>
    <otherwise>
    </otherwise>
      </choose>
    

十二、添加

1.手动提交

sqlSession.commit

2.自动提交

SqlSession sqlSession = sqlSessionFactory.openSession(true);

3. 主键返回

<insert id="add" useGeneratedKeys="true" keyProperty="id">

十三、修改

<set>
</set>

十四、删除

mybatis会将数组参数封装成一个map集合

默认array=数组

collection="array"
void deleteByIds(@Param("ids") int[] ids);

collection="ids"

 <delete id="deleteByIds">
    delete from tb_brand
    where id in
    <foreach collection="ids" item="id" separator="," open="(" close=")">#{id}
    </foreach>;
</delete>

十五、Mybatis参数传递

1.多个参数

  • ParamNameResolver类来进行参数封装

    • 多个参数封装为map集合

      • map.put(“parma1”,参数值1);
      • map.put(“arg0”,参数值1);
      • map.put(“arg1”,参数值2);
      • map.put(“prama2”,参数值2);

2.单个参数

  • pojo类型

    • 直接使用,属性名和参数占位符名称一致
  • map集合

    • 直接使用,键名和参数占位符名称一致
  • collection

    • new HashSet()

      • 封装为map集合

        • map.put(“arg0”,collection集合);
        • map.put(“collection”,collection集合);
  • list

  • array

  • 其他类型

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值