一、if标签
使用动态 SQL 最常见情景,是根据条件包含 where 子句的一部分。
<select id="findActiveBlogLike"
resultType="Blog">
<!-- WHERE与if标签之间尽量加一个条件例如del_flag=0或1=1 -->
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<!-- test:判断表达式(OGNL)
ognl会进行字符串与数字的转换判断 "0"==0
遇见特殊符号应该去写转义字符:&&、''等字符
-->
<if test="title != null">
<!-- AND写在前面,写在后面的话较为奇怪(需要在最后if标签后加1=1) -->
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</select>
二、choose、when、otherwise标签
有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<!-- 用于参数限制,一次只能有一个分支的参数 -->
<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>
</select>
三、trim标签
可以用于等价替代
where标签
和set标签
,
也是上面if标签
提到,如果没有where
后会没有条件的时候使用
- 参数
属性 | 描述 |
---|---|
prefix | 给sql语句拼接的前缀 |
suffix | 给sql语句拼接的后缀 |
prefixOverrides | 去除sql语句前面的关键字或者字符,该关键字或者字符由prefixOverrides属性指定,假设该属性指定为"AND",当sql语句的开头为"AND",trim标签将会去除该"AND" |
suffixOverrides | 去除sql语句后面的关键字或者字符,该关键字或者字符由suffixOverrides属性指定 |
- 替代
where
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG
<trim prefix="WHERE" prefixOverrides="AND">
<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>
</trim>
</select>
- 替代
set
(去除多余的逗号)
<update id="updateAuthorIfNecessary">
update Author
<trim prefix="SET" suffixOverrides=",">
<if test="username != null">username=#{username},</if>
<if test="password != null">password=#{password},</if>
<if test="email != null">email=#{email},</if>
<if test="bio != null">bio=#{bio}</if>
</trim>
where id=#{id}
</update>
三、foreach标签
foreach标签用于对集合进行遍历(尤其是在构建 IN 条件语句的时候)
属性 | 描述 |
---|---|
collection | 参数名称,根据Mapper接口的参数名确定,也可以使用@Param注解指定参数名 |
item | 参数调用名称,通过此属性来获取集合单项的值 |
open | 相当于prefix,即在循环前添加前缀 |
close | 相当于suffix,即在循环后添加后缀 |
index | 索引、下标 |
separator | 分隔符,每次循环完成后添加此分隔符 |
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
<where>
<foreach item="item" index="index" collection="list"
open="ID in (" separator="," close=")" nullable="true">
#{item}
</foreach>
</where>
</select>