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>

 

  

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM