XML中的foreach
foreach元素的属性主要有 collection,item,index,separator,open,close。
collection:表示集合,数据源
在使用foreach的时候最关键的也是最容易出错的就是collection属性,
该属性是必须指定的,但是在不同情况 下,该属性的值是不一样的,
主要有一下3种情况:
如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了
item :表示集合中的每一个元素
index :用于表示在迭代过程中,每次迭代到的位置
separator :表示在迭代时数据以什么符号作为分隔符
open :表示该语句以什么开始
close :表示以什么结束
一、当mapper中参数是单个且是数组的时候
List<String> findName(String[] ids);
xml中的collection是array:
select name from tb1 where id in
<foreach collection="array" item="id" open="(" separator="," close=")">
#{id}
</foreach>
二、当mapper中的参数是单个且是集合的时候
List<String> findName(List ids);
xml中的collection是list:
select name from tb1 where id in
<foreach collection="list" item="id" open="(" separator="," close=")">
#{id}
</foreach>
三、当mapper中的参数是多个,都需要绑定@Param注解,此时xml中collection的值是绑定注解的参数(无论参数是数组还是集合)
List<String> findName(@Param("ids")List names,@Param("age") String data);
或
List<String> findName(@Param("ids")String[] names,@Param("age") String data);
xml中的collection是都是ids:
select name from tb1 where id in
<foreach collection="ids" item="id" open="(" separator="," close=")">
#{id}
</foreach>
四、当mapper中参数是对象,对象中包含参数集合或数组ids的时候
mapper:
List<String> findName(@Param("dto) Student student);
xml:
select name from tb1 where id in
<foreach collection="dto.ids" item="id" open="(" separator="," close=")">
#{id}
</foreach>
五、当sql是插入语句的时候
mapper:
int addStudent(List<Student > students);
insert into Student(name,age)
values
<foreach collection="list" item="entity" separator=",">
(#{entity.name}, #{entity.age})
</foreach>