标签用于实现对于数组与集合的遍历。对其使用,需要注意:
➢ collection 表示要遍历的集合类型, list ,array 等。
➢ open、close、separator 为对遍历内容的 SQL 拼接。
foreach元素的属性主要有item,index,collection,open,separator,close。
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 collection="集合类型" open="开始的字符" close="结束的字符"item="集合中的成员" separator="集合成员之间的分隔符">#{item 的值}</foreach>
(**1) 遍历 List<简单类型>**
表达式中的 List 使用 list 表示,其大小使用 list.size 表示。
需求:查询学生 id 是 1,2,3
接口方法:(if判断中,List的变量名为list)
public abstract List<Student> selectStudentList(List<Integer> listId);
mapper **文件:**
<select id="selectStudentList" resultType="com.wzy.pojo.Student">select id,name,gender,age,birthday,files from student<where><if test="list !=null and list.size > 0">id in<foreach collection="list" open="(" item="listId" close=")" separator=",">#{listId}</foreach></if></where></select>
测试方法:(List集合 变量名为 list)
package com.wzy.dao2;import com.wzy.pojo.Student;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import org.junit.Test;import java.io.IOException;import java.io.InputStream;import java.util.ArrayList;import java.util.List;import static org.junit.Assert.*;public class StudentDao2Test {@Testpublic void selectStudentList() throws IOException {//1.MyBatis 主配置文件String config = "MyBatis2.xml";//2.读取配置文件InputStream resourceAsStream = Resources.getResourceAsStream(config);//3.创建 SqlSessionFactory 对象,用于获取 Dao 代理对象SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(resourceAsStream);//4.获取 Dao代理对象StudentDao2 studentDao2 = factory.openSession().getMapper(StudentDao2.class);//5.创建数据集合List<Integer> list = new ArrayList<>();Collections.addAll(list,1,2,3);//6.调用方法,执行查询List<Student> studentList = studentDao2.selectStudentList(list);//7.输出结果studentList.forEach(student -> System.out.println(student));}}
