mybatis写xml时数字类型用 !=‘‘(不为空串)进行判断的方法

2023-05-15,,

这期内容当中小编将会给大家带来有关mybatis写xml时数字类型用 !=‘‘(不为空串)进行判断的方法,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

样例

下面的是错误示例 ❌

<update id="update" parameterType="com.chengfengfeng.test.domain.People">
    update people
    set
    <if test="age!=null and age !=''">
      age=#{age},
    </if>,
    modified = sysdate()
    where user_id = #{userId}
 </update>

age是个int类型的数据,我们在写age判断的时候就增加上了判断age!='',这个是存在问题的。
正确的示例 ✅

<update id="update" parameterType="com.chengfengfeng.test.domain.People">
    update people
    set
    <if test="age!=null">
      age=#{age},
    </if>,
    modified = sysdate()
    where user_id = #{userId}
 </update>

原因是什么呢

跟踪了下代码,发现在解析xml时数字类型会走下面的判断

public abstract class OgnlOps implements NumericTypes {
	//省略其他无用代码
  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 ? 1.0D : 0.0D;
      } else if (c == Character.class) {
        return (double)(Character)value;
      } else {
        String s = stringValue(value, true);
        //这个位置会把'‘空串处理成0
        return s.length() == 0 ? 0.0D : Double.parseDouble(s);
      }
    }
  }
}

我们看上面最后一段代码,会把''转换成0.0D,那么我们的最开始的if判断就变成了age != 0,所以当我们把age设置为0时,结果就变成了false,导致sql不会进行拼接,更新数据失败。

上述就是小编为大家分享的mybatis写xml时数字类型用 !=‘‘(不为空串)进行判断的方法了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注本站行业资讯频道。

《mybatis写xml时数字类型用 !=‘‘(不为空串)进行判断的方法.doc》

下载本文的Word格式文档,以方便收藏与打印。