MyBatis入门小结

MyBatis配置

为了使用MyBatis,我们需要需要完成以下步骤:

  1. 配置全局配置文件
  2. 配置映射文件
  3. 在全局配置文件中声明映射文件
  4. 获取SqlSessionFactory
  5. 获取sqlSession
  6. 使用sqlSession获取映射文件接口
  1. Mapper接口与XML映射文件绑定,没有实现类,是mybatis为其生成的代理对象
  2. sqlSession是与数据库的一次会话,从而是非线程安全的

两个配置文件

MyBatis中有两个主要的配置文件:

  1. 全局配置文件:用来配置全局属性,包含全局设置、数据库、事务、插件、映射文件的位置

    • 开启驼峰转换:驼峰转化用于结果集的映射(数据库物理字段到实体属性转化),而不是SQL语句中的字段【SQL语句中的查询字段依然是使用物理表中的字段与JPA有很大的不同】
    • 别名转换:预设别名【string int long double float list】
    • 二级缓存:cacheEnabled设置开启二级缓存
    • 懒加载:

      • lazyLoadingEnable:开启懒加载
      • aggressiveLazyLoading:实体中的某个懒加载属性被加载,则该实体中其他懒加载属性也立即被加载,否则按需加载。
  2. 映射文件:主要用来配置SQL编写。

    1. namespace:对应Mapper接口的全类名

映射文件

增删改

  1. 增加:<insert>标签,其主键的获取,可以使用如下的两种方式之一:

    1. <insert useGeneratedKeys="true" keyProperty="id">

      • useGeneratedKeys:使用自增主键
      • keyProperty:将自增主键的值赋给某个属性
    2. 使用<selectKey>编写查找主键的值

      • keyProperty:
      • order:有before与after【在该SQL之前插入还是之后】
      • resultType:指定ID的类型
  2. 删除:<detele>标签,返回值是Boolean、Integer、Long,只需要在Mapper接口中声明即可。
  3. 更新:<update>标签,返回值是Boolean、Integer、Long,只需要在Mapper接口中声明即可。

参数

  1. 单个简单基本参数:名字随便,不用做额外处理
  2. 单个POJO类型:其中的属性会被自动封装成Map的Key和Value
  3. 多个参数:被封装成Map,符号#是从Map中取值,默认key是param1,param2...【可以使用注解@Param来显示指定Key】
  4. 单个参数是List、Set、数组:被封装成Map,名字固定【List的Key是 #{list},,数组的Key是#{array}】
  5. $ 与 #:

    • $:直接放入SQL不进行预编译操作
    • #:使用预编译的形式进行

简单返回值

  1. 放回List类型:直接填写简单类型

    • <select resultType="EmployeeEntity">
  2. 放回Map类型:

    • 单条记录封装:<select resultType="map">【查到了一个数据】
    • 多条记录封装:<select resultType="EmployeeEntity"> + @MapKey("propertyName")【查到了多个数据】

复杂返回值

复杂返回值使用resultMap标签进行结果集封装。在编写resultMap时,建议将所有的列与属性的映射都写上
resultMap用于自定义结果集映射封装。【建议使用resultMap将所有的列都写上!】

  1. <resultMap>
  <resultMap id="" type="EmployeeEntity">
    <id property="id" column="id"/>
    <result property="employeeName" column="employee_name"/>
  </resultMap>
  1. <association>
    <resultMap id="" type="EmployeeEntity">

        <id property="id" column="id"/>
        <result property="employeeName" column="employee_name"/>

<!-- 懒加载配置
   <association property="dept" select="DeptMapper.getDeptById" column="dept_id" fetchType="lazy"/>  
-->
        <association property="department" javaType="DepartmentEntity"> 
            <id property="id" column="id"></id>
            <result property="departmentName" column="department_name"/>
        </association>
    </resultMap>
  1. <collection>
    <resultMap id="" type="DepartmentEntity">

        <id property="id" column="id"/>
        <result property="departmentName" column="department_name"/>
<!-- 懒加载配置
   <collection property="employeeList" 
               ofType="EmployeeEntity" 
               select="DeptMapper.getDeptById" 
               column="dept_id" 
               fetchType="lazy"
            />  
-->
        <collection property="employeeList" ofType="EmployeeEntity">
            <id property="id" column="id"/>
            <result property="employeeName" column="employee_name"/>
        </collection>
    </resultMap>

动态SQL

if

<if test="条件">:test的判断表达式是使用OGNL表达式

    <if test="name != null and name !='' and name.trim() != ''">
          ...
    </if>

choose

<choose>: 类似switch

    <choose>
        <when test="id !=null and id != ''">
            id = #{id}
        </when>
        <when test="name != null and name !=''">
            name = #{name}
        </when>
        <otherwise>
            last_name like #{lastName}
        </otherwise>
    </choose>

where

<where>:自动加上where + 只能够去掉开头的AND

    <where>
        <if test="name != null and name !=''">
            AND name like #{name}
        </if>
         <if test="name != null">
            AND age = #{age}
        </if>
    </where>

set

<set>:自动添加set字句 + 只能去掉最后的逗号

    <update id="updateById">
        update  t_employee
                <set>
                    <if test="name != null">
                        name = #{name},
                    </if>

                    <if test="name != null">
                        age = #{age},
                    </if>
                </set>
    </update>

trim

<trim>: 字符串截取

* `prefix`:`<trim>` 标签拼串结果前面在一个前缀
* `prefixOverrides`:去掉前缀中的字符串
* `suffix`:标签拼串结果前面在一个后缀
* `suffixOverrides`:去掉后缀中的字符串
<!-- 类似<where>标签效果:添加WHERE + 去掉开头的AND -->
<trim prefix="WHERE" prefixOverrides="AND">
        <if test="name != null and name !=''">
            AND name like #{name}
        </if>
        <if test="name != null">
            AND age = #{age}
        </if>
</trim>

foreach

<foreach>:

* collection:传入的参数
* item:定义迭代变量
* open:拼接结果的增加前缀
* close:拼接结果的增加后缀
* separator:迭代结果的类似join()的分隔符
<select>
    select * from t_employee e where e.id in
        <foreach collection="employeeList" item="one" open="(" separator="," close=")" index="i">
            #{id}
        </foreach>
</select>

缓存

Mybatis 将缓存分为两级缓存:

  • 一级缓存:sqlSession级别缓存

    * 查出数据之后,将会自动放入一级缓存中
    
  • 二级缓存:Mapper级别缓存【本质是基于namespace的】,每一个Mapper都维护自己缓存

    * 二级缓存默认**不开启**的,需要手动配置,配置之后将会查询结果将会放入二级缓存【**不同的namespace中**】中
      
一次查询:先查询二级缓存,二级缓存中没有再到一级缓存中,如果一级缓存中没有则到数据库中查找

二级缓存配置

开启二级缓存需要完成下列的三步:

  1. 全局配置文件:配置cacheEnabled,该属性设置二级缓存【只能设置二级缓存】
  2. Mapper.xml:添加标签<cache>

    * `eviction`:缓存回收策略
    * `flushInterval`:多久清空一次
    * `readOnly`:是否只读。
        * 如果设置只读:则Mybatis会直接将缓存的应用给用户
        * 如果设置非只读:则先克隆缓存,然后再交给用户克隆之后的数据
    * `size`:缓存中可以放多少个元素
    * `type`:指定自定义缓存的全类名【实现Mybatis的`Cache`接口】
  3. 缓存的数据实现序列化接口

缓存注意事项

缓存放入策略

查询结果先放入一级缓存中,会话关闭之后,将会话中的缓存放入二级缓存中

缓存失效:

一级缓存:
    * 增删改:一级缓存失效
    * 手动清除一级缓存:`opession.clearCache()`会清除二级缓存
二级缓存:
    * `select`标签的`useCache`:关闭二级缓存
    * 增删改:会清空缓存
    * 增删改标签的`flushCache`:设置`true`将会清空一级缓存,也会清除二级缓存【`select`标签的默认是false】
    * `openSession.clear()`不会清除二级缓存
`localCacheScope`:本地缓存作用域设置STETAMENT会禁用一级缓存。
增删改操作默认会清楚一级缓存和二级缓存

第三方缓存整合

使用第三方缓存可使用如下的一种:

  1. <cache type="缓存类型全类名">:设置二级缓存
  2. <cache-ref="命名空间">:应用其他地方的缓存【直接应用】

其他

  1. <bind>:将OGNL表达式绑定到一个变量上,可以直接被映射文件中引用

    • <bind name="_valName" value="Math.PI">:#{_valName}
  2. <sql> + <include>:

    • <sql>设置SQL片段
    • <include>引用<sql>设置的SQL片段,<include>也可以设置一些变量被<sql>中访问

评论

暂无评论