1、判断Integer类型
private Integer status; //状态, 0,1,2。
<where>
<if test="status != null and status !=''">
and status = #{status }
</if>
</where>
当status的值为0的时候,where条件中的sql未正常拼接,即if test中的条件不成立(false,应该为true才对),
sql拼接失效原因:mybatis在预编译sql时,使用OGNL表达式来解析if标签,对于Integer类型属性,在判断不等于' '时,会返回' '的长度。
String s = stringValue(value, true);
return (s.length() == 0) ? 0.0 : Double.parseDouble(s);
所以表达式 status != ' ' 会被当做 status != 0 来判断,即当 status = 0 的时候,if条件判断不通过,导致动态sql失效。
为了避免这个问题,可以改写成下面这样,去掉对空字符的判断,即可解决问题。
<where>
<if test="status != null">
and status = #{status }
</if>
</where>
2、判断String类型
如果你的字段中存在:String str = "A";
动态sql中写法如:
<if test="str != null and str == 'A'">
and status = #{status }
</if>时
这样写由于单引号内,如果是单个字符的话,OGNL将会识别为java的char类型,而导致str的string类型与char类型做==运算会返回false,导致表达式不成立。
解决如下:
<if test='str != null and str == "A"'>
and status = #{status }
</if>
再比如 jobId 不等于null,并且不等于空字符串,并且不等于字符串"0"
<if test="jobId != null and jobId != '' and jobId != '0'">
AND t.job_id = #{jobId}
</if>
改成
<if test='jobId != null and jobId != "" and jobId != "0"'>
AND t.job_id = #{jobId}
</if>
<if test="jobId != null and jobId == '0'>
AND t.job_group = #{jobGroup}
</if>
改成
<if test='jobId != null and jobId == "0"'>
AND t.job_group = #{jobGroup}
</if>
参考: