mybatis使用in查询(foreach)

本文详细介绍MyBatis中使用foreach标签进行批量查询的方法,包括使用List和Array作为参数,以及通过Map传递多个参数的场景。同时解析了foreach属性如item、index、collection等的作用。

1. findByIds(List ids)
如果参数的类型是List, 则在使用时,collection属性要指定为 list

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

也可以使用org.apache.ibatis.annotations.Param注解,collection对应的就可以使用别名了

findByIds(@Param("ids")List ids)

@Param相当于取了一个别名

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

2:findByIds(Integer[] ids)

如果参数的类型是Array,collection属性要可以指定为 array

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

当然也可以用@Param注解在mapper接口上

findByIds(@Param("ids")Integer[] ids)

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

3.findByMap(@Param("params")Map<String, Object> params)

Map<String, Object> params = new HashMap<String, Object>(2);
params.put("name", "hha");
params.put("ids", ids);  ids是数组或者list都可以  主要是后面遍历ids
<select id="findByMap" resultMap="BaseResultMap">  
 Select  
 <include refid="Base_Column_List" />  
 from user where id in  
 <foreach item="item" index="index" collection="params.ids" open="(" separator="," close=")">  
  #{item}  
 </foreach>  
</select> 

foreach属性主要有item,index,collection,open,separator,close。

1、item表示集合中每一个元素进行迭代时的别名,

2、index指定一个名字,用于表示在迭代过程中,每次迭代到的位置,

3、open表示该语句以什么开始,

4、separator表示在每次进行迭代之间以什么符号作为分隔符,

5、close表示以什么结束,
6、collection属性,如果mapper接口上没有@Param("") 注解的,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的:一般有list和array

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值