问题描述:
使用Mybatis查询数据库,实体类中isFree属性为Integer,请求封装传递过来的值isFree为0,使用如下判断,最终sql语句中始终没有拼接上该条语句
<if test="isFree != null and isFree != ''">
is_free = #{isFree},
</if>
原因分析:
首先可以确定isFree != null
该语句的比较结果为true,问题出在isFree != ''
这条语句,
查阅相关资料发现,Mybatis使用的OGNL表达式来解析的,当isFree为Integer类型并且值为0时,会被解析成空字符串。
有关该问题的源码分析见该文章:mybatis 中 if-test 判断详解
解决方案:
1、对于Integer类型,不需要判断值是否为空串,只有String类型才需要判断,即代码改成
<if test="isFree != null''">
is_free = #{isFree},
</if>
2、对于String类型与单个字符进行比较,单引号加单个字符会被解析成char类型,比较结果也为false,单个字符需要用双引号
<!-- name为String,'a'被解析为char类型,无法比较-->
<if test="name != null and name == 'a' ">
<if>
<!--改成以下写法-->
<if test="name != null and name == "a" ">
<if>