带你学习Mybatis之Mybatis映射文件

Mybatis映射文件

增删改查

简单地增删改查
<select id="selectUser" resultType="User">
    select * from `user` where id = #{id}
</select>

<insert id="addUser">
    insert into `user` (`name`,account) values (#{name},#{account})
</insert>

<update id="updateUser">
    update `user` set `name` = #{name}, account = #{account} where id = #{id}
</update>

<delete id="deleteUser">
    delete from `user` where id = #{id}
</delete>

使用factory.openSession()得到的sqlSession默认不会自动提交,需要手动的提交事务

使用factory.openSession(true)得到的sqlSession自动提交

select详细属性

查询语句是Mybatis中用的最多的

<!-- 
 id 命名空间的唯一标识,一般为方法名,命名空间+id必须唯一
  parameterType   入参类型,该参数可选,mybatis通过类型处理器TypeHandler推断出具体传入的参数
  resultType      返回结果的类全限定名或别名(如果为集合,应设置为集合包含的类型,而不是集合本身的类型)
 resultMap       结果映射(resultType和ResultMap只能同时使用一个)
  flushCache      设置为true,该语句被调用后清空本地缓存和二级缓存,默认false
  useCache        设置为true,该语句结果被二级缓存缓存    select语句默认true
 timeout         等待数据库返回的超时时间
  fetchSize       批量返回的行数
  statementType   可选STATEMENT/PREPARED/CALLABLE  分别对应于Statement/PreparedStatement/CallaleStatement   默认PREPARED
  resultSetType   FORWARD_ONLY/SCROLL_SENSITIVE/SCROLL_INSENSITIVE/DEFAULT
  databaseId      数据库厂商id
  resultOrdered   只针对于嵌套结果select语句:如果为true,将会假设包含了嵌套结果集或是分组,当返回一个主结果行时,就不会产生对前面结果集的引用  确保了在获取嵌套的结果集的时候不至于导致内存不足 默认false
  resultSets      针对于多结果集的情况。将列出语句执行后返回的结果集并赋予每个结果集一个名称,多个名称逗号隔开

sql语句中使用#{id} 则表示使用的是PreparedStatement预处理语句,此时mybatis会创建一个PreparedStatement,在sql中会使用?来标识  select * from `user` where id = ? ,然后在进行赋值  ps.setInt(1,id)
-->

<select
  id="selectUser"    
  parameterType="int"
  resultType="hashmap"
  resultMap="personResultMap"
  flushCache="false"
  useCache="true"
  timeout="10"
  fetchSize="256"
  statementType="PREPARED"
  resultSetType="FORWARD_ONLY">

  select * from `user` where id = #{id}
</select>
insert/update/delete详细属性
<!-- 
 id 命名空间的唯一标识,一般为方法名
  parameterType   入参类型,该参数可选,mybatis通过类型处理器TypeHandler推断出具体传入的参数
  flushCache      设置为true,该语句被调用后清空本地缓存和二级缓存, insert、update、delete语句默认false
 timeout         等待数据库返回的超时时间
  statementType   可选STATEMENT/PREPARED/CALLABLE  分别对应于Statement/PreparedStatement/CallaleStatement   默认PREPARED
  databaseId      数据库厂商id
  useGeneratedKeys  使用JDBC的getGeneratedKeys方法来获取数据库生成的主键,仅对insert有用,默认false
  keyProperty     指定对象的主键属性,将getGeneratedKeys的返回值赋给该属性,如果生成列不止一个,使用逗号隔开,仅对insert有用
  keyColumn       指定生成键值在数据库中的列名,如果生成列不止一个,用逗号隔开
-->


<insert
  id="insertAuthor"
  parameterType="domain.blog.Author"
  flushCache="true"
  statementType="PREPARED"
  keyProperty=""
  keyColumn=""
  useGeneratedKeys=""
  timeout="20">

  
  <update
  id="updateAuthor"
  parameterType="domain.blog.Author"
  flushCache="true"
  statementType="PREPARED"
  timeout="20">

    
  <delete
  id="deleteAuthor"
  parameterType="domain.blog.Author"
  flushCache="true"
  statementType="PREPARED"
  timeout="20">

插入扩展
获取自增id

默认情况下,插入数据后无法获取自增属性的主键id

<!--
    自增主键,mybatis利用statement.getGeneratedKeys()来获取
    useGeneratedKeys="true" 使用自增主键获取主键值策略
    keyProperty  指定对应的主键属性,mybatis获取到主键值后,将值赋给该属性
 -->

<insert id="addUserReturnGeneratedKey" useGeneratedKeys="true" keyProperty="id">
    insert into `user` (`name`,account) values (#{name},#{account})
</insert>
不支持自增主键的方式
<!--
    不支持自增主键的方式
 -->

<insert id="addUserReturnGeneratedKey" databaseId="oracle">
    <!-- 使用selectKey来获取主键序列值
        keyProperty 指定对应的主键属性,mybatis获取到主键值后,将值赋给该属性
        order before表示当前sql在插入sql之前
              after表示当前sql在插入sql之后
        resultType 查出来的数据返回值类型
     -->

    <selectKey keyProperty="id" order="BEFORE" resultType="Integer">
        select user_seq.nextval from dual
    </selectKey>
    insert into `user` (id,`name`,account) values (#{id},#{name},#{account})
</insert>
参数处理
普通的数据类型
User selectUserByIdAndName(@Param("id") int id,@Param("name") String name);
<!-- 测试多个参数取值
    mybatis默认将多个参数封装为一个map
         map的key为param1~paramN
         map的value为传入的参数值
         #{}使用的是map的key来取值
     可以使用命名参数来明确指定封装成map时的key @Param("id") @Param("name")
        map的key为@Param注解指定的名称
        map的value为传入的参数值
 -->

<select id="selectUserByIdAndName" resultType="User">
    select * from user where id = #{id} and name = #{name}
</select>
自定义的java对象数据类型

对于很多入参的情况,不希望方法的入参那么多,而且需要指定@Param参数,可以将这些入参封装为一个对象.

对于对象,可以直接使用字段来进行获取

User selectUserByCondition(User user);
<select id="selectUserByCondition" resultType="User">
        select * from user
        <where>
            <if test="id != null and id != 0">
              and id = #{id}
            </if>
            <if test="name != null">
                and name = #{name}
            </if>
            <if test="account != null and account != 0">
                and account = #{account}
            </if>
        </where>
    </select>
集合属性

对于List,mybatis会映射为list,可以通过list来获取集合中的值

List<User> selectByIds(List<Integer> ids);
<select id="selectByIds" resultType="User">
    select * from user
    <where>
        id in
        <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
    </where>
</select>

结果映射

resultMap和resultType都是作为结果集返回映射

ResultType
使用map

很多情况下使用map作为返回是可以支持的,但是map不是一个很好的领域模型,在获取到数据库结果之后,还需要再去人工的从map中取值给业务需要的字段去赋值,是一件痛苦而繁琐的事情

<select id="selectUser" resultType="map">
  select * from user where id = #{id}
</select>
使用PO

使用PO进行接收结果集时,考虑到数据库中的列名可能与po中的字段名不一致,需要为每个字段起别名,sql写起来就变长了很多

<select id="selectUser" resultType="User">
  select user_id as id,user_name as userName,
  from user where id = #{id}
</select>
ResultMap

由于在使用ResultType时有一些的问题,而且ResultType对于一些复杂的查询结果来说处理起来也并不友好,ResultMap自定义映射的好处就凸显出来了。

<resultMap id="user" type="com.zhanghe.study.mybatis.model.User">
    <!--
         id定义主键
             column 指定数据库的列名
             property 指定java的属性名
       javaType 配置java的类型
       jdbcType 配置数据库类型
             typeHandler  类型处理器
     -->

    <id column="id" property="id"/>
    <!-- 普通的列 -->
    <result column="name" property="name"/>
    <result column="account" property="account"/>
</resultMap>

 <select id="selectUserReturnResultMap" resultMap="user">
     select * from `user` where id = #{id}
 </select>

resultMap是支持继承的

    <resultMap id="base" type="com.zhanghe.study.mybatis.model.User">
        <id column="id" property="id"/>
        <result column="name" property="name"/>
    </resultMap>

    <resultMap id="user01" type="com.zhanghe.study.mybatis.model.User" extends="base">
        
        <result column="account" property="account"/>
    </resultMap>
关联查询一对一

association代表一对一关系

public class Employee {
    private Integer id;
    private String name;
    private double salary;
    private Department department;
}

public class Department {
    private Integer id;
    private String name;
}
级联属性封装
<!-- 级联查询 -->
<resultMap id="emp1" type="com.zhanghe.study.mybatis.model.Employee">
    <id column="id" property="id"/>
    <result column="name" property="name"/>
    <result column="salary" property="salary"/>
   <!-- 使用属性.属性来获取 -->
    <result column="did" property="department.id"/>
    <result column="dname" property="department.name"/>
</resultMap>

<select id="getEmpAndDep" resultMap="emp1">
    select emp.id id,emp.name name,emp.salary salary,emp.dep_id did,dep.name dname from employee emp join department dep on  emp.dep_id = dep.id
    where emp.id = #{id}
</select>
使用association进行join查询
<resultMap id="emp2" type="com.zhanghe.study.mybatis.model.Employee">
    <id column="id" property="id"/>
    <result column="name" property="name"/>
    <result column="salary" property="salary"/>
    <!-- 指定该字段的类型 -->
    <association property="department" javaType="com.zhanghe.study.mybatis.model.Department">
        <id column="did" property="id"/>
        <result column="dname" property="name"/>
    </association>
</resultMap>

<select id="getEmpAndDep" resultMap="emp2">
        select emp.id id,emp.name name,emp.salary salary,emp.dep_id did,dep.name dname from employee emp join department dep on  emp.dep_id = dep.id
        where emp.id = #{id}
</select>
使用association进行分步查询

使用分步查询会执行多条sql语句,先查询出主表,之后将关联列作为条件去通过select来查询子表信息

EmployeeMapper的映射文件

<resultMap id="emp3" type="com.zhanghe.study.mybatis.model.Employee">
    <id column="id" property="id"/>
    <result column="name" property="name"/>
    <result column="salary" property="salary"/>
    <!-- select 当前属性使用select调用的方法
         column 指定将那一列的值作为参数传入select语句
        -->

    <association property="department" column="dep_id"
                 select="com.zhanghe.study.mybatis.mapper.DepartmentMapper.selectDepById">

        <id column="did" property="id"/>
        <result column="dname" property="name"/>
    </association>
</resultMap>

<select id="getEmpAndDep" resultMap="emp3">
   select * from employee where id = #{id}
</select>

DepartmentMapper的映射文件

<resultMap id="dep" type="com.zhanghe.study.mybatis.model.Department">
    <id column="id" property="id"/>
    <result column="name" property="name"/>
</resultMap>

<select id="selectDepById" resultMap="dep">
    select * from department where id = #{id}
</select>

分步查询延迟加载

在使用子表信息的时候在进行查询

在全局配置中开启延迟加载

<settings>
  <setting name="logImpl" value="STDOUT_LOGGING"/>
  <!-- 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType 属性来覆盖该项的开关状态。 -->
  <setting name="lazyLoadingEnabled" value="true"/>
  <!-- 开启时,任一方法的调用都会加载该对象的所有延迟加载属性。 否则,每个延迟加载属性会按需加载 -->
  <setting name="aggressiveLazyLoading" value="false"/>
</settings>
关联查询一对多

使用collection标签代表一对多关系

DepartmentMapper的映射文件

<resultMap id="dep1" type="com.zhanghe.study.mybatis.model.Department">
  <id column="id" property="id"/>
  <result column="name" property="name"/>
  <!-- select 当前属性使用select调用的方法
         column 指定将那一列的值作为参数传入select语句(如果需要多个条件使用{key1=value1,key2=value2})
        -->

  <collection property="employeeList" select="com.zhanghe.study.mybatis.mapper.EmployeeMapper.getEmployeeByDid"
              column="id">

    <id column="id" property="id"/>
    <result column="name" property="name"/>
    <result column="salary" property="salary"/>
    <result column="did" property="department.id"/>
  </collection>
</resultMap>

<select id="getDepAndEmps" resultMap="dep1">
    select * from department where id = #{id}
</select>

EmployeeMapper的映射文件

<resultMap id="emp" type="com.zhanghe.study.mybatis.model.Employee">
 <id column="id" property="id"/>
 <result column="name" property="name"/>
 <result column="salary" property="salary"/>
</resultMap>

<select id="getEmployeeByDid" resultMap="emp">
    select * from employee where dep_id = #{did}
</select>
鉴别器

discriminator鉴别器可以根据某个字段的不同值来进行不同的操作,就像是java中的switch和sql中的case

<resultMap id="baseResultMap" type="Vehicle">
 <id property="id" column="id"/>
  <result property="name" column="name"/>
  <result property="color" column="color"/>
  <discriminator javaType="int" column="type">
    <case value="1" resultType="Car">
     <result property="doorCount" column="door_count"/>
    </case>
    <case value="2" resultMap="vanResult">
     <result property="powerSlidingDoor" column="power_sliding_door"/>
    </case>
  </discriminator>
</resultMap>

${}和#{}之间的区别

{}直接替换成变量的值,不做任何转换,这种是取值以后再去编译SQL语句

#{}:预编译处理,sql中的#{}替换成?,补全预编译语句,调用PreparedStatement的set方法来赋值,有效的防止Sql语句注入,这种取值是编译好SQL语句再取值

sql块

可重用的sql块,可以被其他语句引用

<sql id="userColumns">id,username,password</sql>

<select id="selectUsers" parameterType="int" resultMap="baseResultMap">
 select <include refid="userColumns"/>
  from users
  where id = #{id}
</select>

缓存

默认情况下是没有开启二级缓存的,如果要开启二级缓存,则需要使用<cache/>

  • cache 配置给定命名空间的缓存

    <!--
        eviction: 缓存回收策略
            - LRU  最近最少使用:移除最长时间不被使用的,默认
            - FIFO  先进先出,按照对象进入缓存的顺序移除
            - SOFT  软引用,移除基于垃圾回收器状态和软引用规则的对象
            - WEAK  弱引用,积极地移除基于垃圾收集器状态和弱引用规则的对象

         flushInterval: 缓存刷新间隔
            缓存多长时间清空一次,默认不清空,单位毫秒
         readOnly   默认false
            - true  只读,mybatis认为所有从缓存中获取数据的操作都是只读操作,不会修改数据。mybatis为了加快获取速度,
                    直接将数据在缓存中的引用交给用户,速度快,但是不安全
            - false 非只读,mybatis会认为获取到的数据可能会被修改,会利用序列化和反序列化机制克隆一份新的数据
         size: 缓存多少元素
         type: 指定自定义缓存的全类名,需要实现Cache接口
       blocking: 若缓存中找不到对应的key,是否会一直阻塞,知道对应的数据进入缓存
     -->

    <cache eviction="FIFO" flushInterval="60000" readOnly="true" size="1024"/>
  • cache-ref 从其他命名空间引用缓存配置

    <cache-ref namespace="com.someone.application.data.SomeMapper">

https://zhhll.icu/2021/框架/mybatis/基础/3.mybatis映射文件/

本文由 mdnice 多平台发布

  • 35
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

拾光师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值