choose, when, otherwise

Sometimes we don’t want all of the conditionals to apply, instead we want to choose only one case among many options. Similar to a switch statement in Java, MyBatis offers a choose element.

Let’s use the example above, but now let’s search only on title if one is provided, then only by author if one is provided. If neither is provided, let’s only return featured blogs (perhaps a strategically list selected by administrators, instead of returning a huge meaningless list of random blogs).

  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>