我们学习了如何使用 Mybatis if、where、trim 等动态语句来处理一些简单的查询操作。对于一些 SQL 语句中含有 in 条件,需要迭代条件集合来生成的情况,可以使用 foreach 来实现 SQL 条件的迭代
Mybatis foreach 标签用于循环语句,它很好的支持了数据和 List、set 接口的集合,并对此提供遍历的功能。语法格式如下。
• <foreach item="item" index="index" collection="list|array|map key" open="(" separator="," close=")">
• 参数值
• </foreach>
foreach 标签主要有以下属性,说明如下。
- item:表示集合中每一个元素进行迭代时的别名。比如你是对哪个列的东西进行迭代,则需要填写该列的列名
- index:指定一个名字,表示在迭代过程中每次迭代到的位置。
- open:表示该语句以什么开始(既然是 in 条件语句,所以必然以(括号的左半部分开始)。
- separator:表示在每次进行迭代之间以什么符号作为分隔符(既然是 in 条件语句,所以必然以 , 逗号作为分隔符)。
- close:表示该语句以什么结束(既然是 in 条件语句,所以必然以)括号的右半部分开始)。
使用 foreach 标签时,最关键、最容易出错的是 collection 属性,该属性是必选的,但在不同情况下该属性的值是不一样的,主要有以下 3 种情况:
- 如果传入的是单参数且参数类型是一个 List,collection 属性值为 list。
- 如果传入的是单参数且参数类型是一个 array 数组,collection 的属性值为 array。
- 如果传入的参数是多个,需要把它们封装成一个 Map,当然单参数也可以封装成 Map。Map 的 key 是参数名,collection 属性值是传入的 List 或 array 对象在自己封装的 Map 中的 key。
- Student表中内容
StudentMapper接口文档内容
public List<Student> selectStudent(List<Integer> ageList);
因为我们后续传出的是student,这个是一个数组,因为查出来的内容是不止一个的
而传入的也是一个年龄的数组,因为后续的查询是
SELECT * FROM student where age in (age1,age2)
而后面(age1,age2)是可以看成一个数组,age的类型是integer的类型
StudentMapper.xml中
<select id="selectStudent" parameterType="com.cmj.entity.Student" resultType="com.cmj.entity.Student">
SELECT * FROM student WHERE age in
<foreach collection="list" item="age" index="index" open="(" separator="," close=")">
#{age}
</foreach>
</select>
在我们的test中去写:
private SqlSessionFactory getFactory() throws IOException {
String resource = "mybatis-config.xml";
InputStream is = Resources.getResourceAsStream(resource);
// 初始化mybatis,创建SqlSessionFactory类实例
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
return sqlSessionFactory;
}
///foreach學習
@Test
public void selectStudent() throws IOException {
SqlSession session=getFactory().openSession();
StudentMapper mapper =session.getMapper(StudentMapper.class);
List<Integer> ageList=new ArrayList<Integer>();
ageList.add(3);
ageList.add(6);
List<Student> stuList =mapper.selectStudent(ageList);
for (Student student : stuList) {
System.out.println(student);
}
这样就可以在数据库表中进行循环查出对应年龄在(你需要查询的年龄中)的人员的名单及对应的详细信息