一、概述
在前的文章中介绍了通过association实现分步查询&延迟加载(MyBatis学习–映射文件_select_resultMap_关联查询_association分步查询&&延时加载),以及上一篇文章中通过collection实现级联查询结果集封装(MyBatis学习-映射文件_select_resultMap_关联查询_collection定义关联集合封装规则),这篇文章主要通过collection来实现分步查询&延迟加载。
二、使用场景
这里,以查询某一部门信息,同时查询部门下所有员工信息为例。
- 首先根据部门id查询出部门信息;
- 然后根据查询到的部门信息的部门id查找所有的员工信息
- 将查询的员工信息封装
三、使用collection实现分步查询
- 相关JavaBean
Department.java
public class Department {
private Integer id;
private String departmentName;
private List<Employee> emps;
public List<Employee> getEmps() {
return emps;
}
public void setEmps(List<Employee> emps) {
this.emps = emps;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
@Override
public String toString() {
return "Department [id=" + id + ", departmentName=" + departmentName
+ "]";
}
}
Emlpoyee.java
public class Employee {
private Integer id;
private String lastName;
private String email;
private String gender;
private Department dept;
public Employee() {
super();
}
public Employee(Integer id, String lastName, String email, String gender) {
super();
this.id = id;
this.last