foreach-遍历集合 -笔记要点

 <!--foreach 遍历标签
collection : 指定要遍历的集合;
list类型的参数会特殊处理封装在Map中,map的key就叫做list;
item ; 将当前遍历的元素复制给指定的变量;
separator : 每个元素之间的分隔符!
open : 遍历出所有的结果拼接到一个开始的字符!
close: 遍历出所有的结果拼接一个 结束的字符!
index : 索引,遍历list的时候是索引,
遍历map的时候index表示的就是map的key,item就是map的值;
#{变量名},就能取出变量的值,也就是当前遍历出的元素
-->

出错分析与总结
1.定义接口

  //查询员工id'在给定集合中的
public List<Employee> getEmpsByConditionForeach(@Param("ids")List<Integer> ids);

2.定义XML映射文件

    <!--public List<Employee> getEmpsByConditionForeach(Employee e);-->
<select id="getEmpsByConditionForeach" resultType="com.bean.Employee">
select * from tbl_employee
-- where id in (1,5,6)
<foreach collection="ids" item="item_id" separator=","
open="where id in (" close=")" index="">
#{item_id}
</foreach>
</select>

3.编写测试代码

 public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
return new SqlSessionFactoryBuilder().build(inputStream);
} @Test
public void test11() throws Exception { SqlSession openSession = getSqlSessionFactory().openSession();
try {
System.out.println("++++++++++---- 1.测试 动态SQL元素:foreach!");
EmployeeMapper_DynamicSQL mapper = openSession.getMapper(EmployeeMapper_DynamicSQL.class); List<Employee> list = mapper.getEmpsByConditionForeach(Arrays.asList(1, 2, 3, 4));
for(Employee e:list)
System.out.println(e); openSession.commit();
} finally {
openSession.close();
} }

测试结果:

++++++++++---- 1.测试 动态SQL元素:foreach!
DEBUG 12-05 16:25:49,085 ==> Preparing: select * from tbl_employee -- where id in (1,5,6) where id in ( ? , ? , ? , ? ) (BaseJdbcLogger.java:145)
DEBUG 12-05 16:25:49,104 ==> Parameters: 1(Integer), 2(Integer), 3(Integer), 4(Integer) (BaseJdbcLogger.java:145)
DEBUG 12-05 16:25:49,106 <== Total: 2 (BaseJdbcLogger.java:145)
Employee{id=1, lastName='Jerry2333', email='233@...', gender='1', dept=null}
Employee{id=4, lastName='葫芦娃', email='葫芦娃@163.com', gender='0', dept=null}
05-20 00:37