【MyBatis专题】专题四:动态SQL

if

根据test条件决定是否包含标签内语句

1
2
3
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>

choose、when、otherwise

如果想从多个条件中选择一个使用可以考虑使用 choosewhenotherwise,语法类似于Java中的switch

1
2
3
4
5
6
7
8
9
10
11
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>

where

<where>标签解决的问题是当标签if所有条件都不满足或者中间部分条件满足时,自动去除子句中的ANDORwhere<where>素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。

例如如下示例,当title为空,author不为空时,不使用<where>标签时,SQL语句为:select xxx from xxx where and author = ?,很明显where子句中多了一个and语法错误;使用<where>标签时,MyBatis会自动移除子句中多余的and

1
2
3
4
5
6
7
8
<where>
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>

trim

如果 where 元素与期望的不太一样时,也可以通过自定义 trim 元素来定制 where 元素的功能。

1
2
3
4
<trim prefix="SET" suffixOverrides=",">
<if test="name != null">name = #{name},</if>
<if test="age != null">age = #{age},</if>
</trim>
  • prefix语句拼接前缀
  • prefixOverrides移除指定前缀字符
  • suffix语句拼接后缀字符
  • suffixOverrides移除指定后缀字符

set

set用于动态语句更新,set元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号

1
2
3
4
<set>
<if test="name != null">name = #{name},</if>
<if test="age != null">age = #{age},</if>
</set>

foreach

需要对一个集合进行遍历时可以使用foreach语法进行循环处理(常见与IN参数拼接);允许指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量

1
2
3
4
<foreach item="item" index="index" collection="list"
open="ID in (" separator="," close=")" nullable="true">
#{item}
</foreach>
  • item集合中的元素
  • index元素索引位置
  • list需要遍历的集合,支持ListMapSet或数组,为Map时,index是键,item是值
  • open拼接结果左边开始字符
  • close拼接结果右边结束字符

来源:https://mybatis.org/mybatis-3/zh/dynamic-sql.html


【MyBatis专题】专题四:动态SQL
https://probiecoder.cn/mybatis/dynamic.html
作者
duwei
发布于
2024年5月8日
许可协议