MyBatis 学习(六)之动态 SQL

目录

[1 动态 SQL 介绍](#1 动态 SQL 介绍)

[2 if 标签](#2 if 标签)

[3 where 标签](#3 where 标签)

[4 set 标签](#4 set 标签)

[5 trim 标签](#5 trim 标签)

[6 choose、when、otherwise 标签](#6 choose、when、otherwise 标签)

[7 foreach 标签](#7 foreach 标签)

[8 bind 标签](#8 bind 标签)


1 动态 SQL 介绍

动态 SQL 是 MyBatis 强大特性之一,极大的简化我们拼装 SQL 的操作。MyBatis 的动态 SQL 是基于 OGNL 的( Object Graph Navigation Language ,对象图导航语言),它是一种强大的表达式语言,通过它可以非常方便的来操作对象属性, 类似于 EL,SpEL 等的表达式。动态 SQL 主要有以下几类:

  • if 标签用于条件判断,根据条件是否满足来决定是否包含某个元素。
  • where 标签用于生成 WHERE 子句,并会自动去掉(忽略)第一个条件的 and 或 or 关键字,避免语法错误
  • set 标签 :用于生成 SET 子句,进行更新操作,可以自动处理最后一个条件结尾的逗号
  • trim 标签用于去除或添加前缀和后缀
  • choose、when、otherwise 标签类似于 Java 中的 switch、case、default 语句,根据不同的条件选择执行不同的 SQL 片段
  • foreach 标签用于遍历集合,常用于 IN 语句中的参数列表生成
  • bind 标签用于在 OGNL 表达式之外创建一个变量,并将其绑定到当前的上下文中,以便在后续的表达式中使用

2 if 标签

if 标签,根据条件是否满足来决定是否包含某个元素,判断条件写在 if 标签的 test 属性中

XML 复制代码
<resultMap id="employeeMap" type="com.dao.Employee">
    <id property="empId" column="employee_id"/>
    <result property="empName" column="employee_name"/>
    <result property="empAge" column="employee_age"/>
    <result property="empSex" column="employee_sex"/>
    <result property="empEmail" column="employee_email"/>
    <result property="empAddress" column="employee_address"/>
</resultMap>

<select id="getEmpIf" parameterType="com.dao.Employee" resultMap="employeeMap">
    select * from employee where
    <if test="empName != null and empName != ''">
        employee_name=#{empName}
    </if>
</select>

上述代码如果 if 标签的条件不符合,则查询语句为 select * from employee where,会报错

3 where 标签

where 标签,用于生成 WHERE 子句,并会自动去掉(忽略)第一个条件的 and 或 or 关键字,避免语法错误。

XML 复制代码
<select id="getEmpWhereIf" parameterType="com.dao.Employee" resultMap="employeeMap">
    select * from employee
    <where>
        <if test="empName != null and empName !=''">
            and employee_name=#{empName}
        </if>
    </where>
</select>

通过 where 标签查询,不会出现 SQL 语句多余 where 的情况

4 set 标签

set 标签,用于生成 SET 子句,进行更新操作,可以自动处理最后一个条件结尾的逗号

XML 复制代码
<update id="UpdateEmployee" parameterType="com.dao.Employee">
    update employee
    <set>
        <if test="empName != null and empName !=''">
            employee_name=#{empName},
        </if>
    </set>
    where employee_id=#{empId}
</update>

测试代码需要提交事务,sqlSession.commit(); 否则不会更新数据库

5 trim 标签

trim 标签,用于去除或添加前缀和后缀,以下是 trim 标签的属性:

  • prefix:表示在 trim 标签内的 sql 语句加上前缀
  • suffix:表示在 trim 标签内的 sql 语句加上后缀
  • prefixOverrides:表示去除第一个前缀
  • suffixOverrides:表示去除最后一个后缀
XML 复制代码
<select id="getEmpWhereIf" parameterType="com.dao.Employee" resultMap="employeeMap">
    select * from employee
    <!-- 添加前缀 where,移除 and 或 or -->
    <trim prefix="where" prefixOverrides="and | or">
        <if test="empName != null">
            and employee_name=#{empName}
        </if>
    </trim>
</select>

6 choose、when、otherwise 标签

choose、when、otherwise 标签,类似于 Java 中的 switch 语句,根据不同的条件选择执行不同的 SQL 片段

XML 复制代码
<select id="selectEmployeeByChoose" resultType="com.dao.Employee" parameterMap="employeeMap">
    select * from employee
    <where>
        <choose>
            <when test="empName!= null and empName!=''">
                employee_name=#{empName}
            </when>
            <when test="empAddress!= null and empAddress!=''">
                and employee_address=#{empAddress}
            </when>
            <otherwise>
                and employee_age=#{empAge}
            </otherwise>
        </choose>
    </where>
</select>

7 foreach 标签

foreach 标签,用于遍历集合,常用于 IN 语句中的参数列表生成。foreach 标签有以下几个属性:

  • collection:表示要遍历的集合元素,注意不要写 #{}。
  • item:表示每次遍历时生成的对象名(当传入 Map 对象或 Map.Entry 对象的集合时,index 是键,item 是值)
  • index:表示在迭代过程中,每次迭代到的位置
  • open:表示开始遍历时要拼接的字符串
  • close:表示结束遍历时要拼接的字符串
  • sperator:表示在每次遍历时,两个对象之间的连接字符串
java 复制代码
在 Mapper.xml SQL 映射文件
<select id="selectEmployeeByListId" resultMap="employeeMap">
    select * from employee
    <where>
        <!-- where employee_id in (?,?,?,?)-->
<!--        <foreach collection="ids" item="id" open="employee_id in (" close=")" separator=",">-->
<!--            #{id}-->
<!--        </foreach>-->
        <!-- where employee_id=? or employee_id=?... -->
        <foreach collection="ids" item="id" separator="or">
            employee_id=#{id}
        </foreach>
    </where>
</select>

在 Mapper.java 接口
List<Employee> selectEmployeeByListId(@Param("ids") List<Integer> ids);

在 Test 测试类
@Test
public void testSelectByListid() {
    List<Integer> ids = new ArrayList<>();
    ids.add(1);
    ids.add(2);
    ids.add(4);
    ids.add(5);
    List<Employee> employees = mapper.selectEmployeeByListId(ids);
    for (Employee employee : employees) {
        System.out.println(employee);
    }
}

8 bind 标签

bind 标签,用于在 OGNL 表达式之外创建一个变量,并将其绑定到当前的上下文中,以便在后续的表达式中使用。

XML 复制代码
<!-- 查询姓马的员工 -->
<select id="selectEmployeeByName" parameterType="com.dao.Employee" resultMap="employeeMap">
    <bind name="pattern" value="'%' + empName + '%'"/>
    select * from employee where employee_name like #{pattern}
</select>
相关推荐
执笔论英雄6 小时前
【大模型学习cuda】入们第一个例子-向量和
学习
wdfk_prog6 小时前
[Linux]学习笔记系列 -- [drivers][input]input
linux·笔记·学习
Gary Studio8 小时前
rk芯片驱动编写
linux·学习
mango_mangojuice8 小时前
Linux学习笔记(make/Makefile)1.23
java·linux·前端·笔记·学习
程序员侠客行8 小时前
Mybatis连接池实现及池化模式
java·后端·架构·mybatis
lingggggaaaa9 小时前
安全工具篇&动态绕过&DumpLsass凭据&Certutil下载&变异替换&打乱源头特征
学习·安全·web安全·免杀对抗
PP东9 小时前
Flowable学习(二)——Flowable概念学习
java·后端·学习·flowable
学电子她就能回来吗9 小时前
深度学习速成:损失函数与反向传播
人工智能·深度学习·学习·计算机视觉·github
AI视觉网奇11 小时前
ue 角色驱动衣服 绑定衣服
笔记·学习·ue5
张3蜂11 小时前
深入理解 Python 的 frozenset:为什么要有“不可变集合”?
前端·python·spring