★学习目标:
掌握<foreach>元素对List数组的迭代,能够在代码中熟练使用<foreach>元素对List的迭代
★思考任务:
<foreach>元素对List的迭代的过程是怎么样的?
★任务学习:
★知识要点:
在上一节中,使用<foreach>元素完成了客户信息的批量查询操作,方法参数为一个数组,现在我们更改参数类型,传入一个List类型的参数来实现同样的需求。<foreach>元素迭代List的实现步骤具体如下。在映射文件CustomerMapper.xml中,添加使用<foreach>元素迭代List集合执行批量查询操作的动态SQL。
<select id="findByList" parameterType="java.util.Arrays"
resultType="com.itheima.pojo.Customer">
select * from t_customer where id in
<foreach item="id" index="index" collection="list"
open="(" separator="," close=")">
#{id}
</foreach>
</select>
在测试类MyBatisTest中,编写测试方法findByListTest(),用于批量查询客户信息。
public void findByListTest() {
SqlSession session = MyBatisUtils.getSession();
List<Integer> ids=new ArrayList<Integer>();
ids.add(1); ids.add(2);
List<Customer> customers = session.selectList("com.itheima.mapper"
+ ".CustomerMapper.findByList", ids);
for (Customer customer : customers) {System.out.println(customer);
} session.close();
}
执行MyBatisTest测试类的findByListTest()方法,控制台会输出结果。


