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>
