zoukankan      html  css  js  c++  java
  • mybatis 拼接的字符串查询失效原因以及解决方案

      java 代码

      

    String a="'1','2'";

      xml sql

      

    <select id="queryByCardIds" resultType="java.util.Map" parameterType="java.lang.String">
        
        select * from user where id in (#{a}) 
        </select>

    执行过程: mybatis 是sql动态绑定,当传入一个字符串参数时,框架转换成 map 存储参数,然后再匹配对应的sql模板参数,进行变量替换,组装成可执行的sql 语句。#{a} 会被替换成对应的变量值。
      eg(1): String a="'1','2'"; xml 模板 select * from user where id in (#{a});
      生成的sql: select * from user where id in (''1','2'') 【查询失败】 前后增加 引号

      eg(2): String a="1,2"; xml 模板 select * from user where id in (#{a});
      生成的sql: select * from user where id in ('1,2') 【查询失败】 前后增加 引号

      eg(3): String a="1','2"; xml 模板 select * from user where id in (#{a});
      生成的sql: select * from user where id in ('1'',''2'') 【查询失败】 前后增加引号, 识别字符串内的引号再增加引号

      eg(4): String a="'1','2'"; xml 模板 select * from user where id in (${a}); sql注入风险
      生成的sql: select * from user where id in ('1','2') 【查询成功】 

    总结:mybatis的动态绑定,当用#{} 方式接收,变量值前后会自动添加‘’,目的【防止sql 注入】,若字符串内有引号 (1','2),【【 会对引号特殊处理(再加引号)】】( '1'',''2' )。

      正确的写法 :用 list array 或者 对象 来接收参数

      foreach 使用

     <select id="query" resultType="com.Person" parameterType="java.util.List">
            select name where name in
            <foreach collection="list" item="item" open="(" separator="," close=")" >
               #{item}
            </foreach>
        </select>

      

  • 相关阅读:
    内嵌汇编简介(转)
    binary hacks读数笔记(dlopen、dlsym、dlerror、dlclose)
    在Ubuntu 20.04 LTS Focal Fossa上安装Fail2ban
    如何在CentOS 8上安装和配置Fail2ban
    Linux中使用Head命令的7种方法
    如何在CentOS / RHEL上安装Nginx
    如何在Fedora 32/31/30上安装NVM?
    如何在Ubuntu 20.04 LTS Focal Fossa上安装WildFly?
    如何在CentOS 8上安装oVirt虚拟机管理器
    如何在CentOS 8上安装CentOS Web面板?
  • 原文地址:https://www.cnblogs.com/blogxiao/p/14365449.html
Copyright © 2011-2022 走看看