<foreach/>标签用于实现对于数组与集合的遍历。对其使用,需要注意:
1)collection 表示要遍历的集合类型, list ,array 等。
2) open、close、separator 为对遍历内容的 SQL 拼接。
语法:
<foreach collection="集合类型" open="开始的字符" close="结束的字符" item="集合中的成员" separator="集合成员之间的分隔符">
#{item 的值}
</foreach>下面来说说代码:第一种foreach表示方法
StudentDao接口
//foreach 1 List<Student> selectforeachone(List<Integer> idlist);
StudentDao.xml文件
<!-- foreach 第一种方式 循环List collection:表示循环的对象是list集合还是数组(只能是这两者) 。dao接口形参是数组 collection=“array” ,dao接口形参是list ,collection="list" open:循环开始时的字符。sb.append("("); close:循环结束时字符 sb.append(")"); item:集合成员,定义的变量 。 相当于从新命名 Integer a= list.get(i); separator: 集合成员之间的分割符。sb.append(”,“); #{item} 使用获取的值。 获取从新命名 --> <select id="selectforeachone" resultType="com.liuhaiyang.domain.Student"> <include refid="selectStudent"/> <if test="list!=null and list.size>0" > <!-- foreach和if连用,去除空值现象 list表示传进来的集合--> where id in <foreach collection="list" open="(" close=")" separator="," item="myid"> #{myid} </foreach> </if> </select>
测试类
@Test public void testSelectforeachone() { SqlSession session = MybatisUtils.getSqlSession(); StudentDao dao = session.getMapper(StudentDao.class); List<Integer> list=new ArrayList<>(); list.add(10001); list.add(10009); list.add(100011); // list.add(null); List<Student> stu = dao.selectforeachone(list); stu.forEach(s -> System.out.println("查询结果====>" + s)); //关闭sqlsession session.close(); }
结果截图:
foreach的第二种方式代码如下
StudentDao接口
//foreach 2 List<Student> selectforeachtwo(List<Student> studentlist);
StudentDao.xml文件
<!-- foreach 的第二种方式 传过来的是list student对象 --> <select id="selectforeachtwo" resultType="com.liuhaiyang.domain.Student"> select * from student <if test="list!=null and list.size>0"> where id in <foreach collection="list" open="(" close=")" separator="," item="stu"> #{stu.id} <!-- 这里用stu.id表示 stu是student对象 .id是对象的属性id--> </foreach> </if> </select>
test测试类
@Test public void testSelectforeachtwo() { SqlSession session = MybatisUtils.getSqlSession(); StudentDao dao = session.getMapper(StudentDao.class); List<Student> studentlist=new ArrayList<>(); Student s1=new Student(); s1.setId(10001); Student s2=new Student(); s2.setId(100010); studentlist.add(s1); studentlist.add(s2); // Student s3=new Student(); // s3.setId(null); // studentlist.add(s3); List<Student> stu = dao.selectforeachtwo(studentlist); stu.forEach(s -> System.out.println("查询结果====>" + s)); //关闭sqlsession session.close(); }
结果截图: