• MyBatis入参为0时失效问题


       测试表的表结构

          

          测试表的结果

       

      mapper映射文件

      如果是基本的查询,没有动态sql,传入0,只会查到一条记录。

    <resultMap id="BaseResultMap" type="com.raisecom.ems.pon.system.model.acap.CfmMd" >
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="name" property="name" jdbcType="VARCHAR" />
        <result column="score" property="score" jdbcType="INTEGER" />
      </resultMap>
    
    <select id="selectBySocre" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
        select
        <include refid="Base_Column_List" />
        from test_integer_0
        where score = #{score}
      </select>

      如果是动态sql,传入0,则会报错

      

            报错信息如下

              

      需要修改mapper文件,加上  or score == 0",就不会报错了。

      

      问题的原因可以看看  https://www.cnblogs.com/mengw/p/12056205.html

      MyBatis条件查询对字段判断是否为空一般为:

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

      如果传入参数为Integer类型且值为0时,会把0转为空串

      源码真实情况是:

      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="testValue!=null and testValue!='' or 0 == testValue">
        and test_value = #{testValue}
    </if>
    
    或者
    
    <if test="testValue!=null">
        and test_value = #{testValue}
    </if>
     
     
     
  • 相关阅读:
    java开发编码规范
    Spring Boot 配置文件密码加密两种方案
    qmake生成VS的vcproj/sln工程文件
    R语言爬取动态网页之环境准备
    R实现pm2.5地图数据展示
    【Yii系列】最佳实践之后台业务框架
    【Yii系列】Yii2.0基础框架
    【Python系列】Python自动发邮件脚本-html邮件内容
    【PHP系列】PHP组件详解
    【Yii系列】错误处理和日志系统
  • 原文地址:https://www.cnblogs.com/lnlvinso/p/14802402.html
Copyright © 2020-2023  润新知