choose、when、otherwise

有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。

还是上面的例子,但是策略变为:传入了 “title” 就按 “title” 查找,传入了 “author” 就按 “author” 查找的情形。若两者都没有传入,就返回标记为 featured 的 BLOG(这可能是管理员认为,与其返回大量的无意义随机 Blog,还不如返回一些由管理员精选的 Blog)。

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