使用foreach标签遍历泛型为基本类型的list

例:根据id查询学生信息

  1. 在接口StudentDao中添加方法:
public List<Student> searchStudentEachArray(List<Integer> list); //使用foreach遍历list
  1. 在映射文件StudentMapper.xml中添加语句:
<select id="searchStudentEachList" resultType="com.hbfu.entity.Student">  
	select * from student 
	<if test='list!=null and list.size>0'>  
		where id in 
		<foreach collection="list" open="(" close=")" item="mid" separator=",">  
			#{mid} 
		foreach>  
	if>  
select>
  1. 在接口StudentDao实现类StudentDaoImpl中添加方法:
@Override  
public List<Student> searchStudentEachList(List<Integer> list) {  
    SqlSession session = null;  
    List<Student> studentList = new ArrayList<Student>();  
    try {  
        session = MyBatisUtil.getSession();  
        studentList = session.selectList("com.hbfu.dao.StudentDao.searchStudentEachList",list);  
    }catch (Exception e){  
        e.printStackTrace();  
    }finally {  
        MyBatisUtil.closeSession();  
    }  
    return studentList;  
}
  1. 在测试类StudentTest中添加代码:
Scanner scanner = new Scanner(System.in);  
System.out.println("请输入要查询的学生的id(id间用,隔开):");  
String id= scanner.nextLine();  
String ids[] = id.split(",");  
List<Integer> idlist = new ArrayList<Integer>();  
for (String i: ids) {  
    idlist.add(Integer.parseInt(i));  
}  
System.out.println(studentDao.searchStudentEachList(idlist));

你可能感兴趣的:(SSM,java,MyBatis)