阅读文本大概须要3分钟。程序员
在作mybatis的mapper.xml文件的时候,时常遇到一些须要批量操做的状况,这个时候mybatis的foreach标签就派上用场了。web
foreach元素的属性主要有item,index,collection,open,separator,close。
sql
item:集合中元素迭代时的别名,该参数为必选。数组
index:在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选微信
open:foreach代码的开始符号,通常是(和close=")"合用。经常使用在in(),values()时。该参数可选mybatis
separator:元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号致使sql错误,如in(1,2,)这样。该参数可选。架构
close: foreach代码的关闭符号,通常是)和open="("合用。经常使用在in(),values()时。该参数可选。app
collection: 要作foreach的对象,做为入参时,List对象默认用"list"代替做为键;数组对象有"array"代替做为键;Map对象没有默认的键。固然在做为入参时能够使用@Param("keyName")来设置键,设置keyName后,list和array将会失效。除了入参这种状况外,还有一种做为参数对象的某个字段的时候。举个例子:若是User有属性List ids。入参是User对象,那么这个collection = "ids"。若是User有属性Ids ids;其中Ids是个对象,Ids有个属性List id;入参是User对象,那么collection = "ids.id"编辑器
在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,可是在不一样状况下,该属性的值是不同的,主要有如下3种状况: url
若是传入的是单参数且参数类型是一个List的时候,collection属性值为list 。
若是传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array 。
若是传入的参数是多个的时候,就须要把它们封装成一个Map了,固然单参数也能够封装成Map。实际上若是在传入参数的时候,在MyBatis里面也是会把它封装成一个Map的,map的key就是参数名,因此这个时候collection属性值就是传入的List或array对象在本身封装的map里面的key。
0x01:传入的参数为List
对应的Dao中的Mapper文件是:
public List<User> selectByIds(List<Integer> userIds);
xml文件代码片断:
<select id="selectByIds" resultType="com.olive.pojo.User">
select * from t_user where id in
<foreach collection="list" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
0x02: 传入的参数为Array
对应的Dao中的Mapper文件是:
public List<User> selectByIds(int[] userIds);
xml文件代码片断:
<select id="selectByIds" resultType="com.olive.pojo.User">
select * from t_user where id in
<foreach collection="array" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
0x03: 传入的参数为Map
对应的Dao中的Mapper文件是:
public List<User> selectByIds(Map<String, Object> params);
xml文件代码片断:
<select id="selectByIds" resultType="com.olive.pojo.User">
select * from t_user where id in
<foreach collection="userIds" index="index" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
Map的时候须要注意的是:collection的值ids是存储在map中的key,好比:
map.put("userIds",userIds));
尤为须要注意;
☆
往期精彩
☆
关注我
天天进步一点点
本文分享自微信公众号 - JAVA乐园(happyhuangjinjin88)。
若有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一块儿分享。