mybatis where 中in的使用

当咱们使用mybatis时,在where中会用到 in 如:sql

where name in ('Jana','Tom');数组

咱们能够在sql中直接写 name in ('Jana','Tom') 或者 name in (${names})  (备注:String names = "'Jana','Tom'"; 使用$时会引发sql注入安全问题)安全

可是咱们没法在sql中直接写 name in (#{names});mybatis

会报参数个数错误,由于'Jana','Tom'会被解析成两个传参函数

String[] names={"Jana","Tom"};spa

此时要用foreach函数:code

 

name in
<foreach collection="names" item="name" index="index" open="(" close=")" separator=",">
    #{name}
</foreach>

 

解析为:blog

name in (?,?),而后利用names传入参数string

关于参数的形式,能够是数组形式能够是List形式:it

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>
相关文章
相关标签/搜索