• 彻底搞懂Mybatis


    1.说说什么是MyBatis?

    先吹一下:

    Mybatis 是一个半 ORM(对象关系映射)框架,它内部封装了 JDBC,开发时只需要关注 SQL语句本身,不需要花费精力去处理加载驱动、创建连接、创建statement 等繁杂的过程。程序员直接编写原生态 sql,可以严格控制 sql
    执行性能,灵活度高。
    MyBatis 可以使用 XML 或注解来配置和映射原生信息,将 POJO 映射成数据库中的记录,避免了几乎所有的 JDBC代码和手动设置参数以及获取结果集。

    再说一下缺点

    SQL语句的编写工作量较大,尤其当字段多、关联表多时,对开发人员编写SQL语句的功底有一定要求SQL语句
    依赖于数据库,导致数据库移植性差,不能随意更换数据库

    为什么说Mybatis是半自动ORM映射工具?它与全自动的区别在哪里?

    Hibernate属于全自动ORM映射工具,使用Hibernate查询关联对象或者关联集合对象时,可以根据对象关系模型直接获取,所以它是全自动的。
    而Mybatis在查询关联对象或关联集合对象时,需要手动编写SQL来完成,所以,被称之为半自动ORM映射工具。

    JDBC编程有哪些不足之处,MyBatis是如何解决的?

    1、数据连接创建、释放频繁造成系统资源浪费从而影响系统性能
    解决:在mybatis-config.xml中配置数据链接池,使用连接池统一管理数据库连接。
    2、sql语句写在代码中造成代码不易维护
    解决:将sql语句配置在XXXXmapper.xml文件中与java代码分离。
    3、向sql语句传参数麻烦,因为sql语句的where条件不一定,可能多也可能少,占位符需要和参数一一对应。
    解决:Mybatis自动将java对象映射至sql语句。
    4、对结果集解析麻烦,sql变化导致解析代码变化,且解析前需要遍历,如果能将数据库记录封装成pojo对象解析比较方便。
    解决:Mybatis自动将sql执行结果映射至java对象。

    2.Hibernate 和 MyBatis 有什么区别?

    不同点

    映射关系

    MyBatis 是一个半自动映射的框架,配置Java对象与sql语句执行结果的对应关系,多表关联关系配置简单
    Hibernate 是一个全表映射的框架,配置Java对象与数据库表的对应关系,多表关联关系配置复杂 SQL优化和移植性

    Hibernate 对SQL语句封装,提供了日志、缓存、级联(级联比 MyBatis 强大)等特性,此外还提供 HQL(HibernateQuery Language)操作数据库,数据库无关性支持好,但会多消耗性能。如果项目需要支持多种数据库,代码开发量少,但SQL语句优化困难。

    MyBatis 需要手动编写 SQL,支持动态SQL、处理列表、动态生成表名、支持存储过程。开发工作量相对大些。直接使用SQL语句操作数据库,不支持数据库无关性,但sql语句优化容易。

    MyBatis和Hibernate的适用场景?

    Hibernate 是标准的ORM框架,SQL编写量较少,但不够灵活,适合于需求相对稳定,中小型的软件项目,比如:办公自动化系统

    MyBatis 是半ORM框架,需要编写较多SQL,但是比较灵活,适合于需求变化频繁,快速迭代的项目,比如:电商网站

    3.MyBatis使用过程?生命周期?

    在这里插入图片描述

    4.在mapper中如何传递多个参数?

    在这里插入图片描述
    方法1:顺序传参法

    public User selectUser(String name, int deptId);
    
    <select id="selectUser" resultMap="UserResultMap">
        select * from user
        where user_name = #{0} and dept_id = #{1}
    </select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    #{}里面的数字代表传入参数的顺序。
    这种方法不建议使用,sql层表达不直观,且一旦顺序调整容易出错。

    方法2:@Param注解传参法

    public User selectUser(@Param("userName") String name, int @Param("deptId") deptId);
    
    <select id="selectUser" resultMap="UserResultMap">
        select * from user
        where user_name = #{userName} and dept_id = #{deptId}
    </select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    #{}里面的名称对应的是注解@Param括号里面修饰的名称。
    这种方法在参数不多的情况还是比较直观的,(推荐使用)。

    方法3:Map传参法

    public User selectUser(Map<String, Object> params);
    
    <select id="selectUser" parameterType="java.util.Map" resultMap="UserResultMap">
        select * from user
        where user_name = #{userName} and dept_id = #{deptId}
    </select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    #{}里面的名称对应的是Map里面的key名称。
    这种方法适合传递多个参数,且参数易变能灵活传递的情况。

    方法4:Java Bean传参法

    public User selectUser(User user);
    
    <select id="selectUser" parameterType="com.jourwon.pojo.User" resultMap="UserResultMap">
        select * from user
        where user_name = #{userName} and dept_id = #{deptId}
    </select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    #{}里面的名称对应的是User类里面的成员属性。
    这种方法直观,需要建一个实体类,扩展不容易,需要加属性,但代码可读性强,业务逻辑处理方便,推荐使用。(推荐使用)。

    5.实体类属性名和表中字段名不一样 ,怎么办?

    第1种:通过在查询的SQL语句中定义字段名的别名,让字段名的别名和实体类的属性名一致。

    <select id="getOrder" parameterType="int" resultType="com.jourwon.pojo.Order">
           select order_id id, order_no orderno ,order_price price form orders where order_id=#{id};
    </select>
    
    • 1
    • 2
    • 3

    第2种:通过resultMap 中的来映射字段名和实体类属性名的一一对应的关系。

    <select id="getOrder" parameterType="int" resultMap="orderResultMap">
     select * from orders where order_id=#{id}
    </select>
        
    <resultMap type="com.jourwon.pojo.Order" id="orderResultMap">
        <!–用id属性来映射主键字段–>
        <id property="id" column="order_id">
        <!–用result属性来映射非主键字段,property为实体类属性名,column为数据库表中的属性–>
     <result property ="orderno" column ="order_no"/>
     <result property="price" column="order_price" />
    </reslutMap>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    6.Mybatis是否可以映射Enum枚举类?

    Mybatis当然可以映射枚举类,不单可以映射枚举类,Mybatis可以映射任何对象到表的一列上。映射方式为自定义一个TypeHandler,实现TypeHandler的setParameter()和getResult()接口方法。
    TypeHandler有两个作用,一是完成从javaType至jdbcType的转换,二是完成jdbcType至javaType的转换,体现为setParameter()和getResult()两个方法,分别代表设置sql问号占位符参数和获取列查询结果。

    7.#{}和${}的区别?

    #{}是占位符,预编译处理;${}是拼接符,字符串替换,没有预编译处理。
    Mybatis在处理#{}时,#{}传入参数是以字符串传入,会将SQL中的#{}替换为?号,调用PreparedStatement的set方法来赋值。
    #{} 可以有效的防止SQL注入,提高系统安全性;${} 不能防止SQL 注入
    #{} 的变量替换是在DBMS 中;${} 的变量替换是在 DBMS 外
    
    • 1
    • 2
    • 3
    • 4

    8.模糊查询like语句该怎么写?

    1 ’%${question}%’ 可能引起SQL注入,不推荐
    2 “%”#{question}“%” 注意:因为#{…}解析成sql语句时候,会在变量外侧自动加单引号’ ',所以这里 % 需要使用双引号" ",不能使用单引号 ’ ',不然会查不到任何结果。
    3 CONCAT(’%’,#{question},’%’) 使用CONCAT()函数,(推荐✨)
    4 使用bind标签(不推荐)

    <select id="listUserLikeUsername" resultType="com.jourwon.pojo.User">
    &emsp;&emsp;<bind name="pattern" value="'%' + username + '%'" />
    &emsp;&emsp;select id,sex,age,username,password from person where username LIKE #{pattern}
    </select>
    
    • 1
    • 2
    • 3
    • 4

    9.Mybatis能执行一对一、一对多的关联查询吗?

    当然可以,不止支持一对一、一对多的关联查询,还支持多对多、多对一的关联查询。
    在这里插入图片描述
    一对一

    比如订单和支付是一对一的关系,这种关联的实现:
    实体类:

    public class Order {
        private Integer orderId;
        private String orderDesc;
    
        /**
         * 支付对象
         */
        private Pay pay;
        //……
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    结果映射

    <!-- 订单resultMap -->
    <resultMap id="peopleResultMap" type="cn.fighter3.entity.Order">
        <id property="orderId" column="order_id" />
        <result property="orderDesc" column="order_desc"/>
        <!--一对一结果映射-->
        <association property="pay" javaType="cn.fighter3.entity.Pay">
            <id column="payId" property="pay_id"/>
            <result column="account" property="account"/>
        </association>
    </resultMap>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    查询就是普通的关联查

    <select id="getTeacher" resultMap="getTeacherMap" parameterType="int">
            select * from order o 
             left join pay p on o.order_id=p.order_id
            where  o.order_id=#{orderId}
        </select>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    一对多
    比如商品分类和商品,是一对多的关系。
    查询

    查询就是一个普通的关联查询

       <!-- 关联查询分类和产品表 -->
            <select id="listCategory" resultMap="categoryBean">
                select c.*, p.* from category  c 
                left join product_ p on c.id = p.cid
            </select>  
    
    • 1
    • 2
    • 3
    • 4
    • 5

    实体类

    public class Category {
        private int categoryId;
        private String categoryName;
      
        /**
        * 商品列表
        **/
        List<Product> products;
        //……
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    结果映射

           <resultMap type="Category" id="categoryBean">
                <id column="categoryId" property="category_id" />
                <result column="categoryName" property="category_name" />
         
                <!-- 一对多的关系 -->
                <!-- property: 指的是集合属性的值, ofType:指的是集合中元素的类型 -->
                <collection property="products" ofType="Product">
                    <id column="product_id" property="productId" />
                    <result column="productName" property="productName" />
                    <result column="price" property="price" />
                </collection>
            </resultMap>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    10.Mybatis是否支持延迟加载?原理?

    Mybatis支持association关联对象和collection关联集合对象的延迟加载,association指的就是一对一,collection指的就是一对多查询。在Mybatis配置文件中,可以配置是否启用延迟加载lazyLoadingEnabled=true|false。
    它的原理是,使用CGLIB创建目标对象的代理对象,当调用目标方法时,进入拦截器方法,比如调用a.getB().getName(),拦截器invoke()方法发现a.getB()是null值,那么就会单独发送事先保存好的查询关联B对象的sql,把B查询上来,然后调用a.setB(b),于是a的对象b属性就有值了,接着完成a.getB().getName()方法的调用。这就是延迟加载的基本原理。
    当然了,不光是Mybatis,几乎所有的包括Hibernate,支持延迟加载的原理都是一样的。

    11.如何获取生成的主键?

    新增标签中添加:keyProperty=" ID " 即可

    <insert id="insert" useGeneratedKeys="true" keyProperty="userId" >
        insert into user( 
        user_name, user_password, create_time) 
        values(#{userName}, #{userPassword} , #{createTime, jdbcType= TIMESTAMP})
    </insert>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    这时候就可以完成回填主键

    mapper.insert(user);
    user.getId;
    
    • 1
    • 2

    12.MyBatis支持动态SQL吗?

    在这里插入图片描述
    if

    根据条件来组成where子句

    <select id="findActiveBlogWithTitleLike"
         resultType="Blog">
      SELECT * FROM BLOG
      WHERE state = ‘ACTIVE’
      <if test="title != null">
        AND title like #{title}
      </if>
    </select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    choose (when, otherwise)

    这个和Java 中的 switch 语句有点像

    <select id="findActiveBlogLike"
         resultType="Blog">
      SELECT * FROM BLOG WHERE state = ‘ACTIVE’
      <choose>
        <when test="title != null">
          AND title like #{title}
        </when>
        <when test="author != null and author.name != null">
          AND author_name like #{author.name}
        </when>
        <otherwise>
          AND featured = 1
        </otherwise>
      </choose>
    </select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    trim (where, set)

    <select id="findActiveBlogLike"
         resultType="Blog">
      SELECT * FROM BLOG
      <where>
        <if test="state != null">
             state = #{state}
        </if>
        <if test="title != null">
            AND title like #{title}
        </if>
        <if test="author != null and author.name != null">
            AND author_name like #{author.name}
        </if>
      </where>
    </select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    可以用在动态更新的时候

    <update id="updateAuthorIfNecessary">
      update Author
        <set>
          <if test="username != null">username=#{username},</if>
          <if test="password != null">password=#{password},</if>
          <if test="email != null">email=#{email},</if>
          <if test="bio != null">bio=#{bio}</if>
        </set>
      where id=#{id}
    </update>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    where可以用在所有的查询条件都是动态的情况

    foreach

    <select id="selectPostIn" resultType="domain.blog.Post">
      SELECT *
      FROM POST P
      <where>
        <foreach item="item" index="index" collection="list"
            open="ID in (" separator="," close=")" nullable="true">
              #{item}
        </foreach>
      </where>
    </select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    13.MyBatis如何执行批量操作?

    在这里插入图片描述
    第一种方法:使用foreach标签

    foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。foreach标签的属性主要有item,index,collection,open,separator,close。

    item   表示集合中每一个元素进行迭代时的别名,随便起的变量名;
    index   指定一个名字,用于表示在迭代过程中,每次迭代到的位置,不常用;
    open   表示该语句以什么开始,常用“(”;
    separator 表示在每次进行迭代之间以什么符号作为分隔符,常用“,”;
    close   表示以什么结束,常用“)”。

    在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的,主要有以下3种情况:

    如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
    如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
    如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在MyBatis里面也是会把它封装成一个Map的,
    map的key就是参数名,所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key

    <!-- MySQL下批量保存,可以foreach遍历 mysql支持values(),(),()语法 --> //推荐使用
    <insert id="addEmpsBatch">
        INSERT INTO emp(ename,gender,email,did)
        VALUES
        <foreach collection="emps" item="emp" separator=",">
            (#{emp.eName},#{emp.gender},#{emp.email},#{emp.dept.id})
        </foreach>
    </insert>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    <!-- 这种方式需要数据库连接属性allowMutiQueries=true的支持
     如jdbc.url=jdbc:mysql://localhost:3306/mybatis?allowMultiQueries=true -->  
    <insert id="addEmpsBatch">
        <foreach collection="emps" item="emp" separator=";">                                 
            INSERT INTO emp(ename,gender,email,did)
            VALUES(#{emp.eName},#{emp.gender},#{emp.email},#{emp.dept.id})
        </foreach>
    </insert>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    第二种方法:使用ExecutorType.BATCH

    Mybatis内置的ExecutorType有3种,默认为simple,该模式下它为每个语句的执行创建一个新的预处理语句,单条提交sql;而batch模式重复使用已经预处理的语句,并且批量执行所有更新语句,显然batch性能将更优;但batch模式也有自己的问题,比如在Insert操作时,在事务没有提交之前,是没有办法获取到自增的id,在某些情况下不符合业务的需求。

    具体用法如下:

    //批量保存方法测试
    @Test  
    public void testBatch() throws IOException{
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        //可以执行批量操作的sqlSession
        SqlSession openSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
    
        //批量保存执行前时间
        long start = System.currentTimeMillis();
        try {
            EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
            for (int i = 0; i < 1000; i++) {
                mapper.addEmp(new Employee(UUID.randomUUID().toString().substring(0, 5), "b", "1"));
            }
    
            openSession.commit();
            long end = System.currentTimeMillis();
            //批量保存执行后的时间
            System.out.println("执行时长" + (end - start));
            //批量 预编译sql一次==》设置参数==》10000次==》执行1次   677
            //非批量  (预编译=设置参数=执行 )==》10000次   1121
    
        } finally {
            openSession.close();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    mapper和mapper.xml如下

    public interface EmployeeMapper {   
        //批量保存员工
        Long addEmp(Employee employee);
    }
    
    • 1
    • 2
    • 3
    • 4
    <mapper namespace="com.jourwon.mapper.EmployeeMapper"
         <!--批量保存员工 -->
        <insert id="addEmp">
            insert into employee(lastName,email,gender)
            values(#{lastName},#{email},#{gender})
        </insert>
    </mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    14.说说Mybatis的一级、二级缓存?

    一级缓存: 基于 PerpetualCache 的 HashMap 本地缓存,其存储作用域为SqlSession,各个SqlSession之间的缓存相互隔离,当 Session flush 或 close之后,该 SqlSession 中的所有 Cache 就将清空,MyBatis默认打开一级缓存。

    二级缓存与一级缓存其机制相同,默认也是采用 PerpetualCache,HashMap 存储,不同之处在于其存储作用域为Mapper(Namespace),可以在多个SqlSession之间共享,并且可自定义存储源,如 Ehcache。默认不打开二级缓存,要开启二级缓存,使用二级缓存属性类需要实现Serializable序列化接口(可用来保存对象的状态),可在它的映射文件中配置。

    15.能说说MyBatis的工作原理吗?

    我们已经大概知道了MyBatis的工作流程,按工作原理,可以分为两大步:生成会话工厂、会话运行。在这里插入图片描述

  • 相关阅读:
    drf 请求与响应 编码
    AcWing 109. 天才ACM
    Linux|shell编程|拷贝大文件之显示进度条
    Spring 源码分析(四)——Spring 如何解决循环依赖
    【JVM】 类加载器 ClassLoader
    sql的模糊查询
    C语言11、动态内存管理、柔性数组
    100分钟带你玩转 Spring AOP,轻松吊打面试官
    webpack-merge 实现开发、生产和测试环境的不同配置
    前端基础之《ECMAScript 6(7)—异步技术》
  • 原文地址:https://blog.csdn.net/weixin_42258334/article/details/125520940