明天的明天 永远的永远 未知的一切 我与你一起承担 ??

是非成败转头空 青山依旧在 几度夕阳红 。。。
  博客园  :: 首页  :: 管理

mybatis where 中in的使用

Posted on 2020-11-04 16:16  且行且思  阅读(704)  评论(0编辑  收藏  举报

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

<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>