有時候,我們不想使用所有的條件,而只是想從多個條件中選擇一個使用。針對這種情況,MyBatis 提供了 ?choose
?元素,它有點像 Java 中的 ?switch
?語句。
還是上面的例子,但是策略變?yōu)椋簜魅肓?nbsp;“?title
?” 就按 “?title
?” 查找,傳入了 “?author
?” 就按 “?author
?” 查找的情形。若兩者都沒有傳入,就返回標記為 ?featured
?的 ?BLOG
?(這可能是管理員認為,與其返回大量的無意義隨機 ?Blog
?,還不如返回一些由管理員精選的 ?Blog
?)。
<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>
更多建議: