使用動(dòng)態(tài) SQL 最常見(jiàn)情景是根據(jù)條件包含 ?where
?子句的一部分。比如:
<select id="findActiveBlogWithTitleLike"
resultType="Blog">
SELECT * FROM BLOG
WHERE state = ‘ACTIVE’
<if test="title != null">
AND title like #{title}
</if>
</select>
這條語(yǔ)句提供了可選的查找文本功能。如果不傳入 “?title
?”,那么所有處于 “?ACTIVE
?” 狀態(tài)的 ?BLOG
?都會(huì)返回;如果傳入了 “?title
?” 參數(shù),那么就會(huì)對(duì) “?title
?” 一列進(jìn)行模糊查找并返回對(duì)應(yīng)的 ?BLOG
?結(jié)果(細(xì)心的讀者可能會(huì)發(fā)現(xiàn),“?title
?” 的參數(shù)值需要包含查找掩碼或通配符字符)。
如果希望通過(guò) “?title
?” 和 “?author
?” 兩個(gè)參數(shù)進(jìn)行可選搜索該怎么辦呢?首先,我想先將語(yǔ)句名稱修改成更名副其實(shí)的名稱;接下來(lái),只需要加入另一個(gè)條件即可。
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<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>
更多建議: