foreach
需要注意一点的是:
collection
为set
list
array
时,index
为集合的下标, item
为元素值
collection
为map
时,index
为key
,item
为value
dao
List<Student> listStudents(List<Integer> list);
mapper
<select id="listStudents" resultMap="studentMapper">
select * from `student`
where `id` in
<foreach collection="list" item="value" index="indexOrKey"
open="(" separator="," close=")">
#{value}
</foreach>
</select>
test
@Test
public void test() {
SqlSession session = factory.openSession();
try {
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
List<Integer> listIds = new ArrayList<>();
listIds.add(1000);
listIds.add(10001);
List<Student> students = studentMapper.listStudents(listIds);
if(!students.isEmpty()){
for (Student student:
students) {
System.out.println(student);
}
}else{
System.out.println("没有查到结果!");
}
} finally {
session.commit();
session.close();
}
}