使用Mybatis遇到的坑之Integer类型参数

有时候我们使用实体类传递参数时,有些属性会被设置为Integer类型,比如status、sort等,在这里,使用Integer类型参数作为条件时

要注意一点:例如

<if test="bean.activitySort != null and bean.activitySort !=""">
        AND activity_sort = #{bean.activitySort,jdbcType=VARCHAR}
</if>

这里对于bean.activitySort的判断正常情况下如果activitySort是String类型,先判空,再判断是否是空字符串,这样是正常的,但是如果activitySort是Integer类型参数,那么使用时就需要注意,此处不能对activitySort进行空字符串的判断,因为什么呢?

因为mybatis在解析Integer类型数据时,如果数据值为0,会将0解析为空字符串,这样你传入的参数就成为无效的了,所以正常使用Integer类型参数应该是下面这样:

<if test="bean.activitySort != null">
        AND activity_sort = #{bean.activitySort,jdbcType=VARCHAR}
</if>

Mybatis的xml,Integer类型参数bug问题

当有Integer数据类型的参数值为0时,如pid=0,xml中pid==“” 判断为ture,即不走条件语句

<if test="pid != null and pid != '' ">
   AND a.pid = #{pid}
</if>

正确写法一:还要加上一句 or pid==0

<if test="pid != null and pid != '' or pid ==0">
   AND a.pid = #{pid}
</if>

正确方法二:去掉and pid != ''的条件

<if test="pid != null ">
   AND a.pid = #{pid}
</if>

原因分析

总结