mybatis 参数绑定错误示范(1)

采用xml形式的mybatis

错误示例:

server伪代码为:

java 复制代码
            Map<String, Object> findMapNew = MapUtil.<String, Object>builder()
                    .put("applyUnit", appUnit)
                    .put("planYear", year  != null ? year : -1)
                    .put("code", code)
                    .build();
            List<YearPlan> planList= planDao.checkByMap(findMapNew);

xml

xml 复制代码
select
        t.*
        from plan_year t
        <where>
           t.del_flag = 0 
           and t.status = #{status}
            <if test="applyUnit != null and applyUnit != '' ">
                and t.apply_unit = #{applyUnit}
            </if>            
            <if test="planYear != null ">
                and t.plan_Year = #{planYear}
            </if>
            <if test="code != null and code != '' ">
                and t.code = #{code}
            </if>    
           </where>         

此时,映射的最终sql如下:

sql 复制代码
select
        t.*
        from plan_year t
        where
           t.del_flag = 0 
           and t.status = '111111222222'  ## 单位id
           and t.apply_unit = 2025	## 年份
           and t.plan_Year = 'AABBCCDD'	## CODE

最终报错类型错误

解决方案:

修改xml:

xml

xml 复制代码
select
        t.*
        from plan_year t
        <where>
           t.del_flag = 0 
           <if test="status != null ">
               and t.status = #{status}
            </if>           
           <if test="applyUnit != null and applyUnit != '' ">
                and t.apply_unit = #{applyUnit}
           </if>            
           <if test="planYear != null ">
               and t.plan_Year = #{planYear}
           </if>
           <if test="code != null and code != '' ">
               and t.code = #{code}
           </if>
          </where>           

最终执行正确的sql如下:

sql 复制代码
select
        t.*
        from plan_year t
        where
           t.del_flag = 0 
           and t.apply_unit = '111111222222'  ## 单位id
           and t.plan_Year = 2025	## 年份
           and t.CODE = 'AABBCCDD'	## CODE

原因分析

由于第一次没有对status参数进行判空,导致mybatis在替换参数时用了顺序执行的原则,导致错误产生。

后面修修改了这个错误,进行所有参数进行了判空,正确替换了在server层定义的参数。最终sql按照预期执行。

相关推荐
一只叫煤球的猫2 分钟前
🕰 一个案例带你彻底搞懂延迟双删
java·后端·面试
最初的↘那颗心3 分钟前
Flink Stream API 源码走读 - print()
java·大数据·hadoop·flink·实时计算
JH30731 小时前
Maven的三种项目打包方式——pom,jar,war的区别
java·maven·jar
带刺的坐椅2 小时前
轻量级流程编排框架,Solon Flow v3.5.0 发布
java·solon·workflow·flow·solon-flow
David爱编程2 小时前
线程调度策略详解:时间片轮转 vs 优先级机制,面试常考!
java·后端
阿冲Runner3 小时前
创建一个生产可用的线程池
java·后端
写bug写bug3 小时前
你真的会用枚举吗
java·后端·设计模式
喵手4 小时前
如何利用Java的Stream API提高代码的简洁度和效率?
java·后端·java ee
-Xie-4 小时前
Maven(二)
java·开发语言·maven
IT利刃出鞘4 小时前
Java线程的6种状态和JVM状态打印
java·开发语言·jvm