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 小时前
1.1 从∑到∫:用循环理解求和与累积
java·数据结构·python·算法
维齐洛波奇特利(male)2 小时前
@Pointcut(“execution(* com.hdzx..*(..))“)切入点与aop 导致无限循环
java·开发语言
色空大师2 小时前
【日志文件配置详解】
java·logback·log4j2·日志
迷藏4942 小时前
**发散创新:基于角色与属性的混合权限模型在微服务架构中的实战落地**在现代分布式系统中,
java·python·微服务·云原生·架构
码以致用3 小时前
Java垃圾回收器笔记
java·jvm·笔记
暴力袋鼠哥3 小时前
基于springboot与vue的ai多模态数据展示看板
java·spring boot
用户8307196840823 小时前
VS Code Java开发配置与使用经验分享
java·visual studio code
立莹Sir3 小时前
云原生全解析:从概念到实践,Java技术栈如何拥抱云原生时代
java·开发语言·云原生
程序员老邢3 小时前
【技术底稿 12】内网统一日志系统 Loki + Promtail 全流程部署(对接 Grafana,监控日志一体化)
java·运维·程序人生·grafana·devops