mybatis Integer字段值传0,判断不等于空字符串,识别成空字符串排查解决

mybatis Integer字段值传0,判断不等于空字符串,识别成空字符串排查解决

根本原因:
mybatis将传入的Integer类型的0被识别成空字符串

在mbatis中使用Xml配置sql语句时,出现了这样一个问题。入的参数为0去做判断时,mybatis会把参数0当成是空字符串去判断而引起查询结果错误。

insert into book
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="sno != null" >
        sno,
      </if>
      <if test="sname != null" >
        sname,
      </if>
      <if test="weekRentDiscountFlag != null and weekRentDiscountFlag != ''" >
        week_rentDiscount_flag,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="sno != null" >
        #{sno,jdbcType=INTEGER},
      </if>
      <if test="sname != null" >
        #{sname,jdbcType=VARCHAR},
      </if>
      <if test="weekRentDiscountFlag != null and weekRentDiscountFlag != ''" >
        #{weekRentDiscountFlag,jdbcType=VARCHAR},
      </if>
    </trim>

这样写,当weekRentDiscountFlag =0时,mybatis将不会增加该条件新增,因为mybatis框架会将weekRentDiscountFlag 识别为空字符串。

打印项目中的执行SQL,发现weekRentDiscountFlag=0的时候,不会添加值。

2024-11-22 15:15:49.617 DEBUG 4744 --- [           main] c.s.mapper.BookMapper.insertSelective    : ==>  Preparing: insert into book ( sno, sname ) values ( ?, ? ) 
2024-11-22 15:15:49.731 DEBUG 4744 --- [           main] c.s.mapper.BookMapper.insertSelective    : ==> Parameters: 126(String), test1(String)
2024-11-22 15:15:49.759 DEBUG 4744 --- [           main] c.s.mapper.BookMapper.insertSelective    : <==    Updates: 1

修改之后:去掉 and weekRentDiscountFlag != '' 条件

insert into book
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="sno != null" >
        sno,
      </if>
      <if test="sname != null" >
        sname,
      </if>
      <if test="weekRentDiscountFlag != null" >
        week_rentDiscount_flag,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="sno != null" >
        #{sno,jdbcType=INTEGER},
      </if>
      <if test="sname != null" >
        #{sname,jdbcType=VARCHAR},
      </if>
      <if test="weekRentDiscountFlag != null" >
        #{weekRentDiscountFlag,jdbcType=VARCHAR},
      </if>
    </trim>

打印SQL日志如下:

2024-11-22 15:11:58.351 DEBUG 1432 --- [           main] c.s.mapper.BookMapper.insertSelective    : ==>  Preparing: insert into book ( sno, sname, week_rentDiscount_flag ) values ( ?, ?, ? ) 
2024-11-22 15:11:58.464 DEBUG 1432 --- [           main] c.s.mapper.BookMapper.insertSelective    : ==> Parameters: 126(String), test1(String), 0(Integer)
2024-11-22 15:11:58.476 DEBUG 1432 --- [           main] c.s.mapper.BookMapper.insertSelective    : <==    Updates: 1

解决方案:
1、更改if判断条件:当传入的参数有0时,只判断!=null即可。
2、将字段类型转化为String类型。

posted on 2024-12-05 18:48  oktokeep  阅读(250)  评论(0)    收藏  举报