标签用于实现对于数组与集合的遍历。对其使用,需要注意:
    ➢ collection 表示要遍历的集合类型, list ,array 等。
    ➢ open、close、separator 为对遍历内容的 SQL 拼接。

    foreach元素的属性主要有itemindexcollectionopenseparatorclose

    • 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” 。


    语法:

    1. <foreach collection="集合类型" open="开始的字符" close="结束的字符"
    2. item="集合中的成员" separator="集合成员之间的分隔符">
    3. #{item 的值}
    4. </foreach>

    (**1) 遍历 List<简单类型>**
    表达式中的 List 使用 list 表示,其大小使用 list.size 表示。
    需求:查询学生 id 是 1,2,3

    接口方法:(if判断中,List的变量名为list)

    1. public abstract List<Student> selectStudentList(List<Integer> listId);

    mapper **文件:**

    1. <select id="selectStudentList" resultType="com.wzy.pojo.Student">
    2. select id,name,gender,age,birthday,files from student
    3. <where>
    4. <if test="list !=null and list.size > 0">
    5. id in
    6. <foreach collection="list" open="(" item="listId" close=")" separator=",">
    7. #{listId}
    8. </foreach>
    9. </if>
    10. </where>
    11. </select>

    测试方法:(List集合 变量名为 list)

    1. package com.wzy.dao2;
    2. import com.wzy.pojo.Student;
    3. import org.apache.ibatis.io.Resources;
    4. import org.apache.ibatis.session.SqlSessionFactory;
    5. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    6. import org.junit.Test;
    7. import java.io.IOException;
    8. import java.io.InputStream;
    9. import java.util.ArrayList;
    10. import java.util.List;
    11. import static org.junit.Assert.*;
    12. public class StudentDao2Test {
    13. @Test
    14. public void selectStudentList() throws IOException {
    15. //1.MyBatis 主配置文件
    16. String config = "MyBatis2.xml";
    17. //2.读取配置文件
    18. InputStream resourceAsStream = Resources.getResourceAsStream(config);
    19. //3.创建 SqlSessionFactory 对象,用于获取 Dao 代理对象
    20. SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    21. //4.获取 Dao代理对象
    22. StudentDao2 studentDao2 = factory.openSession().getMapper(StudentDao2.class);
    23. //5.创建数据集合
    24. List<Integer> list = new ArrayList<>();
    25. Collections.addAll(list,1,2,3);
    26. //6.调用方法,执行查询
    27. List<Student> studentList = studentDao2.selectStudentList(list);
    28. //7.输出结果
    29. studentList.forEach(student -> System.out.println(student));
    30. }
    31. }