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

相关推荐
Seven9720 分钟前
Spring AI 框架中如何集成 MCP?
java
开往198231 分钟前
spring boot整合mybatis
java·spring boot·mybatis
北京_宏哥35 分钟前
《刚刚问世》系列初窥篇-Java+Playwright自动化测试-27- 操作单选和多选按钮 - 上篇(详细教程)
java·前端·面试
回家路上绕了弯1 小时前
Java双亲委派机制:从原理到实践的全面解析
java·后端
努力的小郑1 小时前
亿级流量下的生死抉择:Apache BeanUtils vs MapStruct性能差距32倍!架构师选型指南
java·spring·apache
努力的小郑1 小时前
BeanUtils拷贝大对决:Spring与Apache Commons的差异与妙用
java·spring·apache
guojl1 小时前
MyBatis应用案例
后端·mybatis
求知摆渡1 小时前
Spring Boot 3.5 + Spring Cloud Stream:邮件发送与幂等实战
java·spring boot·spring cloud
用户40078422112601 小时前
苍穹外卖实现员工账号启用禁用
java
中东大鹅1 小时前
Mybatis Plus 多数据源
java·数据库·spring boot·后端·mybatis