if

使用动态 SQL 最常见情景是根据条件包含 where 子句的一部分。比如:

1. <select id="findActiveBlogWithTitleLike"
2. resultType="Blog">
3. SELECT * FROM BLOG
4. WHERE state = ‘ACTIVE’
5. <if test="title != null">
6. AND title like #{title}
7. </if>
8. </select>

这条语句提供了可选的查找文本功能。如果不传入 “title”,那么所有处于 “ACTIVE” 状态的 BLOG 都会返回;如果传入了 “title” 参数,那么就会对 “title” 一列进行模糊查找并返回对应的 BLOG 结果(细心的读者可能会发现,“title” 的参数值需要包含查找掩码或通配符字符)。

如果希望通过 “title” 和 “author” 两个参数进行可选搜索该怎么办呢?首先,我想先将语句名称修改成更名副其实的名称;接下来,只需要加入另一个条件即可。

1. <select id="findActiveBlogLike"
2. resultType="Blog">
3. SELECT * FROM BLOG WHERE state = ‘ACTIVE’
4. <if test="title != null">
5. AND title like #{title}
6. </if>
7. <if test="author != null and author.name != null">
8. AND author_name like #{author.name}
9. </if>
10. </select>