当我们使用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>