Mybatis动态查询sql:{choose,when,otherwise}

 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 不会跳出判断语句




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值