坑一:
使用mybatis时,经常会判断属性是否为空。
domain
private Integer status; //状态, 0,1,2。
Mapper.xml
<where>
<if test="status != null and status !=''"> and status = #{status }</if>
</where>
当status的值为0的时候,where条件中的sql未正常拼接,即if test中的条件不成立(false),导致查询结果异常,显然Integer status = 0, 0 != ' ',应该为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>
坑二:
如果你的字段中存在:String str = "A";
动态sql中写法如:<if test="str != null and str == 'A'"> and status = #{status }</if>时
这样写由于单引号内,如果是单个字符的话,OGNL将会识别为java的char类型,而导致str的string类型与char类型做==运算会返回false,导致表达式不成立。
解决如下:
动态sql修改为:
<if test='str != null and str == "A"'> and status = #{status }</if>