改造前:
<if test="customerNewVO.status !=null and customerNewVO.status !='' ">
and a.status = #{customerNewVO.status}
</if>
判断状态不为空即进入SQL拼接
事实上,传入status字段为0时,判断不生效,未进行SQL拼接
改造后:
<if test="customerNewVO.status ==0 || customerNewVO.status !=null and customerNewVO.status !='' ">
and a.status = #{customerNewVO.status}
</if>
添加status字段是否等于0判断,此时SQL进入拼接
问题:为什么在MYBATIS中判断状态为0时不进行SQL拼接?
原因解析:
MYBATIS在预编译SQL时,使用OGNL表达式来解析<if>标签,对于Integer类型属性,
在判断不等于' '时,例如customerNewVO.status != ' ',
OGNL会返回' '的长度,源码:(s.length() == 0) ? 0.0 : Double.parseDouble( s ),
因此表达式customerNewVO.status !=' '被当做customerNewVO.status!= 0来判断,
所以当customerNewVO.status为0时,if条件判断不通过。
整个过程就是customerNewVO.status=0,到XML文件中处理,
MYBATIS会进行处理customerNewVO.status !=0 ===》 customerNewVO.status !='',
所以失效。