一. 知识储备
二. 例子
Department.java
package com.atguigu.mybatis.beans;
import java.util.List;
public class Department {
private Integer id;
private String departmentName;
private List<Employee> emps;
public Department() {
super();
// TODO Auto-generated constructor stub
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
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 getDepartment() {
return departmentName;
}
public void setDepartment(String departmentName) {
this.departmentName = departmentName;
}
@Override
public String toString() {
return "Department [id=" + id + ", department=" + departmentName + "]";
}
}
DepartmentMapperResultMap.java
package com.atguigu.mybatis.dao;
import com.atguigu.mybatis.beans.Department;
public interface DepartmentMapperResultMap {
public Department selectDepartmentAndEmployees(Integer id);
}
DepartmentMapperResultMap.xml
<!-- public Department selectDepartmentAndEmployees(Integer id); -->
<select id="selectDepartmentAndEmployees" resultMap="myDeptAndEmps">
select d.id did, d.dept_name, e.id eid, e.last_name, e.email, e.gender
from tbl_dept d left join tbl_employee e
on d.id = e.d_id where d.id = #{id}
</select>
<resultMap type="com.atguigu.mybatis.beans.Department" id="myDeptAndEmps">
<id column="did" property="id"/>
<result column="dept_name" property="departmentName"/>
<!--
collection:集合类型关联属性
property:关联属性名字
ofType: 指定集合中元素的类型
-->
<collection property="emps" ofType="com.atguigu.mybatis.beans.Employee">
<id column="eid" property="id"/>
<result column="last_name" property="lastName"/>
<result column="email" property="email"/>
<result column="gender" property="gender"/>
</collection>
</resultMap>
TestMyBatisResultMap.java
@Test
public void testResultMapCollection() throws Exception {
SqlSessionFactory ssf = getSqlSessionFactory();
SqlSession session = ssf.openSession();
try {
DepartmentMapperResultMap mapper =
session.getMapper(DepartmentMapperResultMap.class);
Department dept = mapper.selectDepartmentAndEmployees(1);
System.out.println(dept);
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;
}