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

相关推荐
YSRM3 分钟前
Leetcode+Java+图论+最小生成树&拓扑排序
java·leetcode·图论
沐浴露z1 小时前
【JVM】详解 Class类文件的结构
java·jvm·class
桦说编程1 小时前
Java并发编程:两种控制并发度的实现方法及其比较
java·后端
杯莫停丶1 小时前
设计模式之:单例模式
java·单例模式·设计模式
消失的旧时光-19431 小时前
@JvmStatic 的作用
java·开发语言·kotlin
火锅机器1 小时前
java 8 lambda表达式对list进行分组
java·开发语言·list
我是华为OD~HR~栗栗呀2 小时前
华为od-22届考研-测试面经
java·c++·python·功能测试·华为od·华为·面试
是梦终空2 小时前
计算机毕业设计241—基于Java+Springboot+vue的爱心公益服务系统(源代码+数据库+11000字文档)
java·spring boot·vue·毕业设计·课程设计·毕业论文·爱心公益系统
_殊途2 小时前
项目开发手册-项目结构
java