Mybatis中生成动态SQL的标签有四类,分别是:
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
1、if
当需要动态生成where条件时,可以使用if标签:
<select id="findActiveBlogWithTitleLike" resultType="Blog"> SELECT * FROM BLOG WHERE state = ‘ACTIVE’ <if test="title != null and title != ''"> AND title like #{title} </if> </select>
当if中的条件成立时,语句块中的内容将会被加到sql中,多个查询调价可以叠加多个 if标签
2、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>
choose标签只会将第一个成立的<when>标签中的语句加到sql中,如果所有的<when>都不成立,则取otherwise中的语句
3、trim, where, set
在1中的示例中,假定有where条件的情况
WHERE state = ‘ACTIVE’
如果所有where条件都需要动态生成,就需要解决一个问题:谁是第一个条件。
因为where语句中,第一个条件不需要加and(或者or),而第二个之后的条件需要and(或者or),如果你用if标签这样写:
<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> </select>
当所有条件都不匹配时,生成的SQL是这样的:
SELECT * FROM BLOG
WHERE
或者第一个条件不成立,第二个条件成立时,生成的SQL是这样的:
SELECT * FROM BLOG
WHERE
AND title like ‘someTitle’
显然,这都是有语法错误的SQL语句。
Mybatis的Where标签可以解决这个问题
<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>
<where>会自动去除多余的AND 或者OR
类似的,当update语句中set更新相关字段时,也会遇到类似的问题,生成的SQL语句可能会多或者少一个逗号。
Mybatis的<set>标签就是用来解决这个问题的:
<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>
<set>会自动去除多余的逗号
其实,<where>和<set>,都是 通过<trim>实现的:
<trim prefix="WHERE" prefixOverrides="AND |OR "> ... </trim>
<trim prefix="SET" suffixOverrides=","> ... </trim>
<trim>中的<prefix>代表前缀,会插入到生成的条件前面,<prefixOverrides>代表去除前缀,<suffixOverrides>代表去除后缀,多个参数可以用管道符 "|" 分割
4、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>
foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及在迭代结果之间放置分隔符。这个元素是很智能的,因此它不会偶然地附加多余的分隔符。
注意 你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象传递给 foreach 作为集合参数。当使用可迭代对象或者数组时,index 是当前迭代的次数,item 的值是本次迭代获取的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。