MyBatis学习10-动态SQL
1 概述
业务上经常会出现不同条件下需要组装不同的 SQL 语句,使用 Java 代码进行 SQL 语句的组装过于复杂,MyBatis 针对这一痛点,提供了动态 SQL 来解决该问题。动态 SQL 是 MyBatis 的强大特性之一。借助功能强大的基于 OGNL 的表达式,使我们完成复杂 SQL 更为简单。
2 if
if 标签是动态 SQL 中最为常见的一个标签,if 标签示例如下:
<select id="findActiveBlogWithTitleLike"
resultType="Blog">
SELECT * FROM BLOG
WHERE state = ‘ACTIVE’
<if test="title != null">
AND title like #{title}
</if>
</select>
3 choose (when, otherwise)
选择条件如果不想使用所有的条件,只是想从多个条件中选择一个使用,可以使用 choose 标签,示例代码如下:
<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>
4 trim (where, set)
SQL 的拼接经常会出现多余的 and\or, 的问题,为解决该问题,MyBatis 提供了 trim (where, set) 标签进行处理,示例代码如下:
<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>
<trim prefix="WHERE" prefixOverrides="AND">
...
</trim>
<update id="updateAuthorIfNecessary">
update Author
<set>
<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>
</set>
where id=#{id}
</update>
5 foreach
动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候),示例代码如下:
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>