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

相关推荐
Lucky小小吴27 分钟前
ClamAV扫描速度提升6.5倍:服务器杀毒配置优化实战指南
java·服务器·网络·clamav
handsome_sai6 小时前
【Java 线程池】记录
java
大学生资源网7 小时前
基于springboot的唐史文化管理系统的设计与实现源码(java毕业设计源码+文档)
java·spring boot·课程设计
guslegend7 小时前
SpringSecurity源码剖析
java
roman_日积跬步-终至千里8 小时前
【人工智能导论】02-搜索-高级搜索策略探索篇:从约束满足到博弈搜索
java·前端·人工智能
大学生资源网8 小时前
java毕业设计之儿童福利院管理系统的设计与实现(源码+)
java·开发语言·spring boot·mysql·毕业设计·源码·课程设计
JasmineWr8 小时前
JVM栈空间的使用和优化
java·开发语言
Hello.Reader8 小时前
Flink SQL DELETE 语句批模式行级删除、连接器能力要求与实战避坑(含 Java 示例)
java·sql·flink
爱笑的眼睛118 小时前
从 Seq2Seq 到 Transformer++:深度解构与自构建现代机器翻译核心组件
java·人工智能·python·ai
Spring AI学习8 小时前
Spring AI深度解析(10/50):多模态应用开发实战
java·spring·ai