mybatis where 中in的使用

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

 

转载于:https://www.cnblogs.com/blog-yuesheng521/p/11097222.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值