Mybatis---动态查询(choose,when,otherwise)

60 阅读2分钟

有时候我们并不想应用所有的条件,而只是想从多个选项中选择一个。而使用if标签时,只要test中的表达式为 true,就会执行 if 标签中的条件。MyBatis 提供了 choose 元素。if标签是与(and)的关系,而 choose 是或(or)的关系。

choose标签是按顺序判断其内部when标签中的test条件出否成立,如果有一个成立,则 choose 结束。当 choose 中所有 when 的条件都不满则时,则执行 otherwise 中的sql。类似于Java 的 switch 语句,choose 为 switch,when 为 case,otherwise 则为 default。

例如下面例子,同样把所有可以限制的条件都写上,方面使用。choose会从上到下选择一个when标签的test为true的sql执行。安全考虑,我们使用where将choose包起来,放置关键字多于错误。

<choose>
<when test="branchCode != null">
                and bp.branch_company_code = #{branchCode}
</when>
<otherwise>
                and bp.branch_company_code is not null
</otherwise>
</choose>

如果branchCode有值,就加 and bp.branch_company_code = #{branchCode}。如果branchCode没有值,就加and bp.branch_company_code is not null

choose (when,otherwize) ,相当于java 语言中的 switch ,与 jstl 中 的 choose 很类似。

when元素表示当 when 中的条件满足的时候就输出其中的内容,跟 JAVA 中的 switch 效果差不多的是按照条件的顺序,当 when 中有条件满足的时候,就会跳出 choose,即所有的 when 和 otherwise 条件中,只有一个会输出,当所有的我很条件都不满足的时候就输出 otherwise 中的内容。所以上述语句的意思非常简单, 当 title!=null 的时候就输出 and titlte = #{title},不再往下判断条件,当title为空且 content!=null 的时候就输出 and content = #{content},当所有条件都不满足的时候就输出 otherwise 中的内容。

配合使用是等价于java中的

if(...){
....
}else if(...){
...
}else{
....
}

另外补充

  • lt (less than) 小于
  • le (less than or equal to) 小于等于
  • eq (equal to) 等于
  • ne (not equal to) 不等于
  • ge (greater than or equal to)大于等于
  • gt (greater than) 大于