mybatis <if test=""></if>标签0为null

采过一个坑,写篇日志来记录下

<if test="state != null and state != ''">state = #{state}</if>

当状态值设置为0时,操作完了,数据库没反应,没有设置为0
仔细检查了代码,代码没有出错。回避问题的解决办法,把状态用1和2表示,不使用0,一切正常,问题消失了。
出来混的,迟早要还的,后来又遇到这个问题:

<if test="totalNum!= null and totalNum!= ''">total_num = #{totalNum}</if>

当totalNum 传入值为0时,操作结束后,数据库显示为该值不是0,代码没问题,传值也没问题,就是没达到预期的效果,我知道是mybatis里面的问题。世界是最遥远的距离,就是我新手造的bug,它就在那里,可我就是找不出来。经过一番摸索,知道了问题所在:
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;”  
totalNum!= ” 传入0时,表达式的值为false;所以这名不执行。
解决办法,把这个删掉就可以了。

<if test="totalNum!= null">total_num = #{totalNum}</if>

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

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

<if test='str!= null and str == "A"'>

猜你喜欢

转载自blog.csdn.net/every__day/article/details/78964180
今日推荐