<selectid="findActiveBlogWithTitleLike"resultType="Blog"> SELECT * FROM BLOG WHERE state = 'ACTIVE' <iftest="title != null"> AND title like #{title} </if> </select>
这里的SQL语句就提供了选择情景,如果我们不传入title或者传入的title为空,那么就不会拼接 AND title like #{title}
又或者想加入额外的判断:
1 2 3 4 5 6 7 8 9 10
<selectid="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG WHERE state = 'ACTIVE' <iftest="title != null"> AND title like #{title} </if> <iftest="author != null and author.name != null"> AND author_name like #{author.name} </if> </select>
<selectid="findActiveBlogLike"resultType="Blog"> SELECT * FROM BLOG WHERE state = 'ACTIVE' <choose> <whentest="title != null"> AND title like #{title} </when> <whentest="author != null and author.name != null"> AND author_name like #{author.name} </when> <otherwise> AND featured = 1 </otherwise> </choose> </select>
结论:when标签里的 test属性,可以插入并解析OGNL表达式
③ trim (where, set)
1 2 3 4 5 6 7 8 9 10 11 12
<selectid="findActiveBlogLike"resultType="Blog"> SELECT * FROM BLOG WHERE <iftest="state != null"> state = #{state} </if> <iftest="title != null"> AND title like #{title} </if> <iftest="author != null and author.name != null"> AND author_name like #{author.name} </if> </select>
可以看下这个SQL语句,假设如果没有满足匹配的条件,那么最终这条 SQL 会变成这样:
1 2
SELECT * FROM BLOG WHERE
毫无疑问,这会导致查询失败
同样的,如果匹配的只是第二个条件,这条 SQL 会是这样:
1 2 3
SELECT * FROM BLOG WHERE ANDtitlelike'someTitle'
这个查询也会失败
所以mybatis提出来了trim方法,如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
<selectid="findActiveBlogLike"resultType="Blog"> SELECT * FROM BLOG <where> <iftest="state != null"> state = #{state} </if> <iftest="title != null"> AND title like #{title} </if> <iftest="author != null and author.name != null"> AND author_name like #{author.name} </if> </where> </select>
可以看到多了一个where标签,同理还有一个set标签
结论:该情况下,一般没有地方可以供我们插入OGNL表达式
④ foreach
动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)。比如:
1 2 3 4 5 6 7 8 9 10
<selectid="selectPostIn"resultType="domain.blog.Post"> SELECT * FROM POST P <where> <foreachitem="item"index="index"collection="list" open="ID in ("separator=","close=")"nullable="true"> #{item} </foreach> </where> </select>
结论:该情况下,一般没有地方可以供我们插入OGNL表达式
⑤ bind
bind 标签允许我们在 OGNL 表达式以外创建一个变量,并将其绑定到当前的上下文。比如:
1 2 3 4 5
<selectid="selectBlogsLike"resultType="Blog"> <bindname="pattern"value="'%' + _parameter.getTitle() + '%'" /> SELECT * FROM BLOG WHERE title LIKE #{pattern} </select>