mybatis sql in查询语句的使用方法

来源:V型知识库 2017年12月17日 10:17 浏览:3441

昨天在做一个mybatis sql in查询语句,发现传入字符串参数的值为"1,2,3",始终查询出一条数据,由于本人接触mybatis时间不长,所以感觉这个问题非常有趣,就索性各种办法测试,还是一条数据,没办法,只能百度了下,发现一篇关于mybatis sql in查询语句的博文,具体博文如下(注意此博文的介绍有坑):

1. findByIds(List ids)

如果参数的类型是List, 则在使用时,collection属性要必须指定为 list

<select id="findByIdsMap" resultMap="BaseResultMap">  
 Select  
 <include refid="Base_Column_List" />   from jria where ID in  
 <foreach item="item" index="index" collection="list" open="(" separator="," close=")">  
  #{item}  
 </foreach>  
</select>

2:findByIds(Long[] ids)

如果参数的类型是Array,则在使用时,collection属性要必须指定为 array

<select id="findByIdsMap" resultMap="BaseResultMap">  
    select  
    <include refid="Base_Column_List" />  
    from tabs where ID in  
    
</select>

3. findByIds(String name, Long[] ids)

当查询的参数有多个时: 

这种情况需要特别注意,在传参数时,一定要改用Map方式, 这样在collection属性可以指定名称

Map<String, Object> params = new HashMap<String, Object>(2); 
params.put("name", name); 
params.put("ids", ids);
 mapper.findByIdsMap(params);
<select id="findByIdsMap" resultMap="BaseResultMap">
 select
 <include refid="Base_Column_List" />
 from tabs where ID in
 <foreach item="item" index="index" collection="ids" open="(" separator="," close=")">
  #{item}
 </foreach>
</select>

看到此博文,我就测试了下,此博文还强调(第一条和第二条)collection属性要必须指定为 list,可是参数名称明明为ids,你指定list,怎么查找,难道mybatis这么智能,自动识别,带着这个疑问,我也设置list吧,设置好之后,运行程序报错,报错信息如下

如异常信息,已经给你解释的非常清楚了,你明明传参数名为ids,干嘛非要设置list呢,所以我把collection属性要必须指定为list改成 collection属性要必须指定为ids,参数名ids与collection ids保持一致。经测试成功!

如果参数名为ids,代码应该改成如下才可以

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