一. 例子
DepartmentMapperResultMap.java
package com.atguigu.mybatis.dao;
import com.atguigu.mybatis.beans.Department;
public interface DepartmentMapperResultMap {
public Department selectDepartmentAndEmployeesStep(Integer id);
}
EmployeeMapperResultMap.java
package com.atguigu.mybatis.dao;
import java.util.List;
import com.atguigu.mybatis.beans.Employee;
public interface EmployeeMapperResultMap {
public List<Employee> selectEmployeesByDid(Integer did);
}
EmployeeMapperResultMap.xml
<!-- public List<Employee> selectEmployeesByDid(Integer did); -->
<select id="selectEmployeesByDid" resultType="com.atguigu.mybatis.beans.Employee">
select id, last_name, email, gender from tbl_employee where d_id = #{did}
</select>
DepartmentMapperResultMap.xml
<!--
collection 分步查询:
需求:查询部门并且查询部门中所有的员工信息
1. 先根据部门id查询部门的信息
2. 再根据部门id查询员工信息
-->
<!-- public Department selectDepartmentAndEmployeesStep(Integer id); -->
<select id="selectDepartmentAndEmployeesStep" resultMap="myDeptAndEmpsStep">
select id, dept_name from tbl_dept where id = #{id}
</select>
<resultMap type="com.atguigu.mybatis.beans.Department" id="myDeptAndEmpsStep">
<id column="id" property="id"/>
<result column="dept_name" property="departmentName"/>
<collection property="emps"
select="com.atguigu.mybatis.dao.EmployeeMapperResultMap.selectEmployeesByDid"
column="id">
</collection>
</resultMap>
TestMyBatisResultMap.java
@Test
public void testResultMapCollectionStep() throws Exception {
SqlSessionFactory ssf = getSqlSessionFactory();
SqlSession session = ssf.openSession();
try {
DepartmentMapperResultMap mapper =
session.getMapper(DepartmentMapperResultMap.class);
Department dept = mapper.selectDepartmentAndEmployeesStep(1);
System.out.println(dept.getDepartmentName());
System.out.println("------------------------------------");
System.out.println(dept.getEmps());
session.commit();
} finally {
// TODO: handle finally clause
session.close();
}
}
public SqlSessionFactory getSqlSessionFactory() throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream =
Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream);
return sqlSessionFactory;
}