MyBatis 学习(六)之动态 SQL

目录

1 动态 SQL 介绍

2 if 标签

3 where 标签

4 set 标签

5 trim 标签

6 choose、when、otherwise 标签

7 foreach 标签

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 属性中

<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 关键字,避免语法错误。

<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 的情况

set 标签

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

<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(); 否则不会更新数据库

trim 标签

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

  • prefix:表示在 trim 标签内的 sql 语句加上前缀
  • suffix:表示在 trim 标签内的 sql 语句加上后缀
  • prefixOverrides:表示去除第一个前缀
  • suffixOverrides:表示去除最后一个后缀
<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 片段

<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:表示在每次遍历时,两个对象之间的连接字符串
在 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 表达式之外创建一个变量,并将其绑定到当前的上下文中,以便在后续的表达式中使用。

<!-- 查询姓马的员工 -->
<select id="selectEmployeeByName" parameterType="com.dao.Employee" resultMap="employeeMap">
    <bind name="pattern" value="'%' + empName + '%'"/>
    select * from employee where employee_name like #{pattern}
</select>

  • 39
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值