MyBatis中的if标签问题:!=null and !=‘‘ 在Integer 0不适用

问题产生

这是项目中遇到的一个问题,记录下来...
先看mybatis映射xml文件里的一段内容:
<sql id="Page_Where_Clause">
        <trim prefix="where" prefixOverrides="and|or">
<if test="item.extension.offlinePrint != null and item.extension.offlinePrint != ''">
                and (select count(1) from train_order_extension toe where toe.order_no = tod.order_no and
                toe.offline_print = #{item.extension.offlinePrint})
</if>
</trim>
</sql>

这个if标签存在于一个where的条件集里,判断条件为看item.extension.offlinePrint是否为null&&空(为什么这么写,是因为懒,复制了其他的。。。)前端的传参为Integer类型的0
因此,在跑项目过程中,没有拼接上这部分sql语句。也不报错,所以困扰很久。
一开始还以为传参的问题,毕竟item.extension.offlinePrint这样的参数也不确定mybatis能不能解析出来。

解决

MyBatis的表达式是用OGNL处理的。OGNL表达式的规则如下:

Interpreting Objects as Booleans
Any object can be used where a boolean is required. OGNL interprets objects as booleans like this:
 
If the object is a Boolean, its value is extracted and returned;
 
If the object is a Number, its double-precision floating-point value is compared with zero; non-zero is treated as true, zero as false;
 
If the object is a Character, its boolean value is true if and only if its char value is non-zero;
 
Otherwise, its boolean value is true if and only if it is non-null.
根据这一条“If the object is a Number, its double-precision floating-point value is compared with zero; non-zero is treated as true, zero as false;”   

offlinePrint!= ” 传入0时,表达式的值为false;所以这名不执行。
解决办法,把这个删掉就可以了。

			<if test = "item.extension.offlinePrint != null">

          and (select count(1) from train_order_extension toe where toe.order_no = tod.order_no and
                toe.offline_print = #{item.extension.offlinePrint})
            </if>

本来只有String类型的才会进行这样的判断——item.extension.offlinePrint!= ‘’,其实是自己码代码时只顾自制粘贴,自己给自己埋了个坑。

这里有必要再提一个“坑”,如果类似于String str =”A”; 这样的写法时时,根据第三条规则,OGNL将会识别为Java 中的 char类型,显然String 类型与char类型做==运算会返回false,从而导致表达式不成立。解决方法很简单,修改为

我的方法 : 我的方法是删掉 !=’’

参考链接:!=null and !=’’ 并不能防Integer 0

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值