当前位置: 移动技术网 > IT编程>开发语言>Java > mybatis写xml时数字类型千万别用 !=‘‘(不为空串)进行判断的示例详解

mybatis写xml时数字类型千万别用 !=‘‘(不为空串)进行判断的示例详解

2020年09月22日  | 移动技术网IT编程  | 我要评论
前言最近项目内更新数据时,发现数字类型字段设置为0时不能正常的更新进数据库,我们打印了下mybatis的sql日志发现字段为0的sql没有被拼接。样例下面的是错误示例 ❌<upda

前言

最近项目内更新数据时,发现数字类型字段设置为0时不能正常的更新进数据库,我们打印了下mybatis的sql日志发现字段为0的sql没有被拼接。

样例

下面的是错误示例 ❌

<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数字类型内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网