xml中的sql语句foreach字段

https://blog.csdn.net/wenyichuan/article/details/104951428

  1. foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。
  2. foreach元素的属性主要有 item,index,collection,open,separator,close。
  • item表示集合中每一个元素进行迭代时的别名
  • index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置
  • separator表示在每次进行迭代之间以什么符号作为分隔符
  • open表示该语句以什么开始
  • close表示以什么结束。

在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况 下,该属性的值是不一样的,主要有一下3种情况:

  • 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
  • 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
  • 如果传入的参数是Map的时候,collection 的属性值为map 的key值
  • 当使用可迭代对象或者数组时,index 是当前迭代的次数,item 的值是本次迭代获取的元素。
  • 当使用 Map 对象(或者 Map.Entry对象的集合)时,index 是键,item 是值。
    **

举例说明

**

  1. 单参数List类型
List idList =new ArrayList();
idList.add(1);
idList.add(2);
idList.add(3);
List list = alarmService.list(idList); 

map.xml :
select * from vehicle where id in
<foreach item="id" collection="list" open="(" separator="," close=")">
        #{id}
</foreach>

2、传入的值为array

int[] arr  = new int[] {1,3,6,9};
List list = alarmService.list(arr ); 

map.xml :
select * from vehicle where id in
<foreach item="id" collection="array" open="(" separator="," close=")">
        #{id}

3、传入的参数为map

List list =new ArrayList();
 list.add(1);
 list.add(2);
 Map params =new HashMap();
 params.put("vehicleIdList",list);
List alarmList =alarmService.list(params);

map.xml :
<if test="vehicleIdList != null ">and vehicle_id in 
 <foreach item="id" collection="vehicleIdList" open="(" separator="," close=")"> #{id} </foreach> 
</if>
原文地址:https://www.cnblogs.com/JimShi/p/14250506.html