使用foreach标签遍历数组

  1. foreach标签用于实现对数组与集合类型的输入参数的遍历
  2. collection属性表示要遍历的集合类型
  3. separator属性表示间隔符
  4. open属性表示起始
  5. close属性表示结束
  6. item属性值自行设置

例:依据id一次性查询出多为学生信息

  1. 在接口StudentDao中添加方法:
public List<Student> searchStudentEachArray(Object[] ids); //使用foreach标签遍历数组
  1. 在映射文件StudentMapper.xml中添加语句:
<select id="searchStudentEachArray" resultType="com.hbfu.entity.Student">  
	select * from student 
	<if test='array!=null and array.length>0'>  
		where id in 
		<foreach collection="array" open="(" close=")" item="mid" separator=",">  
			#{mid} 
		foreach>  
	if>  
select>
  1. 在接口StudentDao实现类StudentDaoImpl中添加方法:
@Override  
public List<Student> searchStudentEachArray(Object[] ids) {  
    SqlSession session = null;  
    List<Student> studentList = new ArrayList<Student>();  
    try {  
        session = MyBatisUtil.getSession();  
        studentList = session.selectList("com.hbfu.dao.StudentDao.searchStudentEachArray",ids);  
    }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(",");  
System.out.println(studentDao.searchStudentEachArray(ids));

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