Mybatis中使用Collection元素进行一对多级联查询

   Collection主要处理“一对多”类型映射关系,例如,查询部门中有多个员工,就需要使用的到集合:List emp,这样,就会使用collection进行映射关联查询。

1.employee.java

package com.casv.model;

public class employee {

	private int uid;
	private String name;
	private String pwd;
	private department dept;

	public int getUid() {
		return uid;
	}

	public void setUid(int uid) {
		this.uid = uid;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public department getDept() {
		return dept;
	}

	public void setDept(department dept) {
		this.dept = dept;
	}

}
2.department.java

package com.casv.model;

import java.util.List;

public class department {
   
	private int pid;
	private String pname;
	//使用List集合保存员工信息,并关联employee实体类
    private List emplist;
	public int getPid() {
		return pid;
	}
	public void setPid(int pid) {
		this.pid = pid;
	}
	public String getPname() {
		return pname;
	}
	public void setPname(String pname) {
		this.pname = pname;
	}
	public List getEmplist() {
		return emplist;
	}
	public void setEmplist(List emplist) {
		this.emplist = emplist;
	}
	
}
3.deptMapper.xml



    
       
       
       
       
           
		   
		    
       
    
    

ofType属性可以区分是JavaBean(或字段)属性,还是集合包含属性,读作:“在emps对象类型中ArrayList中的emplist集合”。

4.config.xml中注册deptMapper.xml




	
	
		
		
		
	
	
	
		
			
			
				
				
				
				
			
		
	
	
		
		
	
5.编写test测试类
@Test 
public void test2(){
    session=MyBatisUtil.getSessionFactory().openSession();
    department dept=session.selectOne("com.casv.dao.deptMapper.selectDeptFetchEmp", 1);
    for(employee emp : dept.getEmplist()){
	System.out.println(emp.getName()+" "+dept.getPname());
    }
    session.close();
}


你可能感兴趣的:(Mybatis)