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按照预期执行。

相关推荐
2023框框1 分钟前
方法器 --- 策略模式(Strategy Pattern)
java·策略模式
Brookty5 分钟前
【Java学习】定时器Timer(源码详解)
java·开发语言·学习·多线程·javaee
编啊编程啊程1 小时前
gRPC从0到1系列【6】
java·rpc·kafka·dubbo·nio
宸津-代码粉碎机2 小时前
Redis 进阶:跳出缓存局限!7 大核心场景的原理与工程化实践
java·人工智能·redis·python
极客先躯2 小时前
Spring Statemachine 架构详解
java·spring·架构
ccccczy_2 小时前
Java微服务容器化与 Kubernetes 编排实战:从 Docker 多阶段构建到云原生弹性扩展
java·docker·kubernetes·springboot·microservices·cloudnative·containerization
沉木渡香3 小时前
VSCode中Java开发环境配置的三个层级(Windows版)1-3
java·windows·vscode
程序员小白条3 小时前
度小满运维开发一面
java·运维·python·职场和发展·运维开发
Leo655358 小时前
JDK8 的排序、分组求和,转换为Map
java·开发语言
书源丶11 小时前
二十八、API之《System 类》——与系统交互的“桥梁”
java·交互