where pro.enterprise_user_id = #{uid} and pro.status_new!=0
<choose>
<when test='statusNew == "2"'>
AND (pro.status_new = 2 or pro.status_new = 4)
</when>
<when test='statusNew == "1"'>
AND pro.status_new > 1 AND pro.deleted != 1
</when>
<when test='statusNew == "12"'>
AND pro.status_new = 12
</when>
<when test="deleted != null and !deleted.equals('')">
AND pro.deleted = #{deleted}
</when>
<otherwise>
AND pro.status_new > 0
</otherwise>
</choose>
ORDER BY pro.createTime DESC
<choose><when><otherwise>配合使用类似于实现:
if( ) {
}else if( ) {
}else {
}
在使用时候需要特别注意以下几点:
1.<otherwise>需要存在,意思是在之前所有<when>不满足条件的情况下执行:实际开发中遇到过这个问题,没有写,Mybatis不会抱任何错误,但是会查询出表中所有的数据。
<otherwise>
AND pro.status_new > 0
</otherwise>
2.在用==进行数值判断时应该:
<when test='statusNew == "2"'>
AND (pro.status_new = 2 or pro.status_new = 4)
</when>
不应该是:
<when test="statusNew == '2'">
AND (pro.status_new = 2 or pro.status_new = 4)
</when>
mybatis是使用的OGNL表达式来进行解析的,在OGNL的表达式中,’y’会被解析成字符,因为java是强类型的,char 和 一个string 会导致不等。所以if标签中的sql不会被解析。具体的请参照 OGNL 表达式的语法
关注:mybatis 的<choose> <when>标签和<if test >标签的区别
1)choose标签是按顺序判断其内部when标签中的test条件出否成立,如果有一个成立,则 choose 结束。
当 choose 中所有 when 的条件都不满则时,则执行 otherwise 中的sql。类似于Java 的 switch 语句,choose 为 switch,when 为 case,otherwise 则为 default。
2)if-test 不会跳出判断语句