Mybatis参数Integer类型值为0 源码处理

mybatis在做条件查询时,如果传入参数为Integer类型且值为0时,如下代码,status!=''的值为false

为什么?mybatis把0转成空串了?看到网上的答案我差点就信了...

代码示例:

<if test="status!=null and status!=''">
     status = #{status}
</if>

翻了下源码,然而真实情况是这样的:

mybatis解析的所有sqlNode节点,针对if节点会交给IfSqlNode来处理,进过层层处理,最终都会调用OgnlOps.class类的doubleValue(Object value)方法

public static double doubleValue(Object value) throws NumberFormatException {
    if (value == null) {
        return 0.0D;
    } else {
        Class c = value.getClass();
        if (c.getSuperclass() == Number.class) {
            return ((Number)value).doubleValue();
        } else if (c == Boolean.class) {
            return ((Boolean)value).booleanValue() ? 1.0D : 0.0D;
        } else if (c == Character.class) {
            return (double)((Character)value).charValue();
        } else {
            String s = stringValue(value, true);
            return s.length() == 0 ? 0.0D : Double.parseDouble(s);
        }
    }
}

0和""都调用该方法返回的double值都为0.0,在进行比较。

处理方法:

<if test="status!=null and status!='' or 0 == status">
    and status = #{status}
</if>

或者

<if test="status!=null">
    and status = #{status}
</if>

不为别的,就是把真相告诉大家!

猜你喜欢

转载自www.cnblogs.com/gushen-super/p/9238161.html