當我們使用mybatis時,在where中會用到 in 如:
where name in ('Jana','Tom');
我們可以在sql中直接寫 name in ('Jana','Tom') 或者 name in (${names}) (備注:String names = "'Jana','Tom'"; 使用$時會引起sql注入安全問題)
但是我們無法在sql中直接寫 name in (#{names});
會報參數個數錯誤,因為'Jana','Tom'會被解析成兩個傳參
String[] names={"Jana","Tom"};
此時要用foreach函數:
name in <foreach collection="names" item="name" index="index" open="(" close=")" separator=","> #{name} </foreach>
解析為:
name in (?,?),然后利用names傳入參數
關於參數的形式,可以是數組形式可以是List形式:
1.當只傳入names變量時,collection必須指定array或list類型:
public List<User> findInfos(String[] names);
<select id="findInfos" resultMap="UserMap"> SELECT * FROM t_user WHERE id IN <foreach collection="array" item="name" index="index" open="(" close=")" separator=","> #{name} </foreach> </select>
public List<User> findInfos(List<String> names);
<select id="findInfos" resultMap="UserMap"> SELECT * FROM t_user WHERE id IN <foreach collection="list" item="name" index="index" open="(" close=")" separator=","> #{name} </foreach> </select>
注意:array傳入的時候parameterType可以是"Integer[]" ,可以是"int[]",但不可以是"String[]"
報錯 Could not resolve type alias 'string[]'. Cannot find class: string[]
2.當有其他變量時,利用map傳入參數集時,可以直接將變量寫在collection中
Map<String,Object> params = new HashMap<>(); params.put("class",class); params.put("names",names);
<select id="findInfos" resultMap="UserMap"> SELECT * FROM t_user WHERE id IN <foreach collection="names" item="name" index="index" open="(" close=")" separator=","> #{name} </foreach> </select>