Mybatis<if test=“status!= null and status!= '' “>对于Integer 0 并不适用

827 阅读1分钟

前言

摸鱼的时候被通知之前的一个粑粑山有一个bug,没办法呀查查吧

一查竟然是踩了Mybatis <if test="">的坑了,记录下来防止以后再踩

业务逻辑

查询条件里:有这么一个select选择器,三个选项分别对应value: 0,1,2; image.png

对应的查询sql如下:

where 1=1
<if test="query.activation !=null and query.activation !='' and query.activation != 2">
    and sim.activation = #{query.activation}
</if>
<if test="query.activation == 2">
    and (sim.usedFLow = 0 and sim.activation = 1)
</if>
...

Bug:

选择value=0的选项时,这个查询sql并没有拼接 and sim.activation = 0;这显然是有点儿问题的!

排查:

传参是否正确?

首先怀疑是不是参数没传进来,导致 if条件 未满足,从而sql没有进行相应拼接;

这个很好排除,打断点跟一下就确定不是传参的问题;

<if test="">条件判断的问题?

那只能是这个问题了,但是代码中的写法不就是最常用的判空写法嘛,这是我这个没什么经验的人的经验哈哈哈

原因:

MyBatis的表达式是用OGNL处理的。OGNL表达式的规则其中有一条如下:

*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; *

也就是说 当 query.activation = 0 时,!= '' 表达式的值为false

所以这部分sql语句没有被拼接上;

解决办法:

对于Integer类型的值:不加 != '' 的判断;

where 1=1
<if test="query.activation !=null and query.activation != 2">
    and sim.activation = #{query.activation}
</if>
<if test="query.activation == 2">
    and (sim.usedFLow = 0 and sim.activation = 1)
</if>
...

综述

以上这个坑先填上,下次再遇到坑再回来记录!反正那个粑粑山已经烂到一定地步了!从进公司就一直是在维护这个项目,什么时间才能有新项目啊!而且我一个前端,除了前端的活,其它都做了啊,废了废了!蕉绿~