有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。
针对这种情况,我们一般可能会想到用if-else,但在MyBatis中是不支持 if-else 的。
想要是用 if - else 的话,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。
- choose (when, otherwise)
<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>
传入了 “title” 就按 “title” 查找,传入了 “author” 就按 “author” 查找的情形。若两者都没有传入,就返回标记为 featured 的 BLOG。
除了choose (when, otherwise)元素,还有if,trim (where, set),foreach 元素。
如果想了解更多,可以参考MyBatis官方文档:mybatis官方文档动态SQL
本文介绍了在MyBatis中,如何使用choose元素来代替if-else结构处理多条件查询,以及trim(where,set)和foreach的用法,强调了动态SQL在满足不同查询需求时的灵活性。
244





