• Mybatis中Mapper.xml详解


    Mybatis中Mapper.xml详解

    SQL 映射文件只有很少的的几个(按照被定义的顺序列出)

    • cache - 对给定命名空间的缓存配置
    • cache-ref - 对给定的命名空间缓存配置的引用
    • resultMap - 是最复杂也是最强大的元素,用来描述如何从数据库结果集中来加载对象
    • sql - 可被其他语句引用的可重用语句块
    • insert - 映射插入语句
    • update - 映射更新语句
    • delete - 映射删除语句
    • select - 映射查询语句

    官网地址:https://mybatis.net.cn/sqlmap-xml.html

    1.select

    • 查询语句是最长用的元素之一,是用来查询数据。它复杂的点在于查询结果集的映射,但是经过MyBaits 的处理一切都变得非常的简单,比如:
    <select id="findById"  parametreType="int" resultType="blog">
        select * from blog where `id` = #{id}
    select>
    
    • 1
    • 2
    • 3

    2.parameterType

    可选标签。参数类的完全限定名或别名,如果是传参是对象,这是对象的绝对路径,例如:parameterType=“com.hjt.userInfo.entity.SysMenu”。如果是基本数据类型,就直接写。例如:parameterType=“Long”,parameterType=“java.util.List”

    3.resultType

    非必选标签。注意这里的非选是因为resultType和resultMap不能并存,两者能且只能选择一个。主要是用来定义一个返回结果集对象的全限定名或者别名。

    4.resultMap

    非必选标签。注意这里的非选是因为resultType和resultMap不能并存,两者能且只能选择一个。

    resultMap类型的结果集映射,也就是返回值类型(比如接收类型是一个对象:resultMap=“SysMenuResult”)

    <resultMap type="com.hjt.userInfo.entity.SysDept" id="SysDeptResult">
          <id     property="deptId"     column="dept_id"     />
          <result property="parentId"   column="parent_id"   />
          <result property="ancestors"  column="ancestors"   />
          <result property="deptName"   column="dept_name"   />
          <result property="orderNum"   column="order_num"   />
          <result property="leader"     column="leader"      />
          <result property="phone"      column="phone"       />
          <result property="email"      column="email"       />
          <result property="status"     column="status"      />
          <result property="delFlag"    column="del_flag"    />
          <result property="createBy"   column="create_by"   />
          <result property="createTime" column="create_time" />
          <result property="updateBy"   column="update_by"   />
          <result property="updateTime" column="update_time" />
       resultMap>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    也可以返回值是基本数据类型 eg: resultType=“Integer”

    5.insert

    
    <insert id="insert" parameterType="blog">
        insert into blog (`id`, `name`, `title`, `content`)
        values (#{id}, #{name}, #{title}, #{content})
    insert>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    6.update

    
    <update id="update" parameterType="blog">
        update blog
        set `name` = #{name}, `title` = #{title}, `content` = #{title}
        where id = #{id}
    update>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    7.delete

    
    <delete id="delete" parameterType="int">
        delete from blog where id = #{id}
    delete>
    
    • 1
    • 2
    • 3
    • 4

    8.forearch

    collection表示迭代集合的名称
    item表示本次迭代获取的元素,若collection为List、Set或者数组,则表示其中的元素;若collection为map,则代表key-value的value,该参数为必选
    open表示该语句以什么开始,最常用的是左括弧’(’,注意:mybatis会将该字符拼接到整体的sql语句之前,并且只拼接一次,该参数为可选项
    close表示该语句以什么结束,最常用的是右括弧’)’,注意:mybatis会将该字符拼接到整体的sql语句之后,该参数为可选项
    separatormybatis会在每次迭代后给sql语句append上separator属性指定的字符,该参数为可选项
    index在list、Set和数组中,index表示当前迭代的位置,在map中,index代指是元素的key,该参数是可选项。

    8.1 forearch批量查询

    	<select id="testSelectAllSysDeptByDeptId"  resultType="com.hjt.userInfo.entity.SysDept">
    		<include refid="selectDeptVo">include>
    		where d.dept_id in
    		<foreach collection="deptIds" item="item" 
    				 separator="," open="(" close=")">
    			#{item}
    		foreach>
    
    	select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    /***
     * 根据deptId查询全部
     * @param deptIds split(',')
     * @return
     */
    List<SysDept> testSelectAllSysDeptByDeptId(@Param("deptIds") List<Long> deptIds);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    实际执行的样子:

    ==>  Preparing: select d.dept_id, d.parent_id, d.ancestors, d.dept_name, d.order_num, d.leader, d.phone, d.email, d.status, d.del_flag, d.create_by, d.create_time from sys_dept d where d.dept_id in ( ? , ? , ? , ? )
    
    • 1

    先看第一个foreach:
    1、是在括号里有多个参数,所以要open="(“开始,close=”)“结束,separator=”,"作为中间的分隔

    2.@Param(“deptIds”) List deptIds中的 deptIds要和

    /**
    
    批量插入用户信息
    *
    
    @param userList
    
    @return
    */
    int insertList(List<SysUser> userList);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    8.2 forearch批量插入

    <insert id="insertList" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO sys_user(user_name, user_password, user_email, user_info, head_img, create_time)
        VALUES
        <foreach collection="list" item="user" separator=",">
            (#{user.userName},#{user.userPassword},#{user.userEmail},#{user.userInfo},#{user.headImg,jdbcType=BLOB},#{user.createTime,jdbcType=TIMESTAMP})
        foreach>
    insert>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    DEBUG [main] - ==> Preparing: INSERT INTO sys_user(user_name, user_password, user_email, user_info, head_img, create_time) VALUES (?,?,?,?,?,?) , (?,?,?,?,?,?)

    8.3 forearch批量修改

    <update id="updateDeptNameById" parameterType="java.util.List">
       update sys_dept set dept_name =
        <foreach collection="sysDeptDtos" item="item" open="case dept_id" close="end"
               separator=" ">
        when #{item.deptId} then #{item.deptName}
        foreach>
        where dept_id in
        <foreach collection="sysDeptDtos" item="item" index="index"
               separator="," open="(" close=")">
           #{item.deptId}
        foreach>
    
    update>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    /***
     * 批量修改
     * @param sysDeptDtos
     */
    void updateDeptNameById(@Param("sysDeptDtos")List<SysDeptDto> sysDeptDtos);
    
    • 1
    • 2
    • 3
    • 4
    • 5

    实际执行语句

    ==> Preparing: update sys_dept set dept_name = case dept_id when ? then ? when ? then ? end where dept_id in ( ? , ? )
    > Parameters: 366(Long), 测试3(String), 367(Long), 测试4(String), 366(Long), 367(Long)
    <
    Updates: 2

    9.include

    事先写好sql语句

    <sql id="selectMenuVo">
           select menu_id, menu_name, parent_id, order_num, path, name, component, iframe_url, is_frame, is_cache, menu_type, visible, status, ifnull(perms,'') as perms, icon, create_time
       from sys_menu
       sql>
    
    • 1
    • 2
    • 3
    • 4

    eg:

    <select id="checkMenuNameUnique" parameterType="com.hjt.userInfo.entity.SysMenu" resultMap="SysMenuResult">
       <include refid="selectMenuVo"/>
       where menu_name=#{menuName} and parent_id = #{parentId} limit 1
    select>
    
    • 1
    • 2
    • 3
    • 4

    10.if

    <update id="updateDept" parameterType="com.hjt.userInfo.entity.SysDept">
          update sys_dept
          <set>
             <if test="parentId != null and parentId != 0">parent_id = #{parentId},if>
             <if test="deptName != null and deptName != ''">dept_name = #{deptName},if>
             <if test="ancestors != null and ancestors != ''">ancestors = #{ancestors},if>
             <if test="orderNum != null and orderNum != ''">order_num = #{orderNum},if>
             <if test="leader != null">leader = #{leader},if>
             <if test="phone != null">phone = #{phone},if>
             <if test="email != null">email = #{email},if>
             <if test="status != null and status != ''">status = #{status},if>
             <if test="updateBy != null and updateBy != ''">update_by = #{updateBy},if>
             update_time = sysdate()
          set>
          where dept_id = #{deptId}
    update>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    11.trim

    mybatis的trim标签一般用于去除sql语句中多余的and关键字,逗号,或者给sql语句前拼接 “where“、“set“以及“values(“ 等前缀,或者添加“)“等后缀,可用于选择性插入、更新、删除或者条件查询等操作。

    属性 描述
    prefix 给sql语句拼接的前缀
    suffix 给sql语句拼接的后缀
    prefixOverrides 去除sql语句前面的关键字或者字符,该关键字或者字符由prefixOverrides属性指定,假设该属性指定为"AND",当sql语句的开头为"AND",trim标签将会去除该"AND"
    suffixOverrides 去除sql语句后面的关键字或者字符,该关键字或者字符由suffixOverrides属性指定

    首先来看一个问题

    <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>
    select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    如果这些条件没有一个能匹配上会发生什么?最终这条 SQL 会变成这样:

    SELECT * FROM BLOG WHERE
    
    • 1

    可以用where标签或者trim标签来解决这个问题

    
    	
    	  state = #{state}
    	 
    	
    	  AND title like #{title}
    	
    	
    	  AND author_name like #{author.name}
    	
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    也可以用下面的where来解决

    12.where

    <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
  • 相关阅读:
    Javascript中for循环基础练习题弹出输入框接收班级人数,根据人数接收分数,计算班级平均数与总分数
    使用Python+selenium实现第一个自动化测试脚本
    go调用 c++中数组指针相关
    search_engine:搜索引擎实现
    嵌入式linux系统中图片处理详解
    Linux·软中断&tasklet
    Jenkins+Python自动化测试持续集成详细教程
    ios xcode 15 PrivacyInfo.xcprivacy 隐私清单
    机器学习算法基础--逻辑回归
    【Hack The Box】windows练习-- Timelapse
  • 原文地址:https://blog.csdn.net/weixin_40483369/article/details/127763075