一、标签foreach作用
编写mybatis中的mapper.xml文件时,我们可使用<foreach>
标签将数组或列表等数据类型动态生成适用于查找的sql语句。
例如将数据string[] ids= {'1','2','3'}
转换为 ('1','2','3')
二、标签foreach的主要属性
-
item:集合中元素迭代时的别名,该参数为必选。
-
index:在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选
-
open:foreach代码的开始符号,一般是(和close=")"合用。常用在in(),values()时。该参数可选
-
separator:元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选。
-
close: foreach代码的关闭符号,一般是)和open="("合用。常用在in(),values()时。该参数可选。
-
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的使用
1、mapper.xml 中的代码
<if test="instruStatusArray != null and instruStatusArray!= ''">
and instru_status in
<foreach collection="instruStatusArray" item="item" index="index"
open="(" separator="," close=")" >
#{item}
</foreach>
</if>
<if test="pd.instruNo != null and pd.instruNo!= ''">
and instru_no like concat('%', #{pd.instruNo}, '%')
</if>
2、mapper中的代码
List<PageData> getInstrumentList(@Param("pd") PageData pd,@Param("instruStatusArray") String[] instruStatusArray);
3.serviceImpl中的代码
public List<PageData> getInstrumentList(PageData pd) {
List<PageData> list = instrumentMapper.getInstrumentList(pd,pd.getString("instruStatus").split(","));
return list;
}
四、说明
- 由于mapper向xml中传递了两个参数,所以用
@Param("")
标记了两个键值分别为:
instruStatusArray在之后的xml中使用@Param("pd") PageData pd,@Param("instruStatusArray") String[]
<if>
标签时采取这种方式pd.instruNo
获取变量instruNo中的数据。