通过collection处理一对多的映射关系
- collection:处理一对多的映射关系(处理集合类型的属性)
- collection标签的属性 ofType :设置collection标签所处理的集合属性中存储数据的类型
- 部门对应员工是一对多的关系
![](https://img-blog.csdnimg.cn/2f1d8a13e28844a99483c5c06fd85ec7.png)
DeptMapper 接口
public interface DeptMapper {
/**
* 查询部门以及部门中的员工信息
* @param deptId
* @return
*/
Dept getDeptAndEmpByDeptId(@Param("deptId") Integer deptId);
}
MyBatis的映射文件 DeptMapper.xml
<resultMap id="deptAndEmpResultMap" type="Dept">
<id column="dept_id" property="deptId"></id>
<result column="dept_name" property="deptName"></result>
<collection property="emps" ofType="Emp">
<id column="emp_id" property="empId"></id>
<result column="emp_name" property="empName"></result>
<result column="age" property="age"></result>
<result column="gender" property="gender"></result>
</collection>
</resultMap>
<!--Dept getDeptAndEmpByDeptId(@Param("deptId") Integer deptId);-->
<select id="getDeptAndEmpByDeptId" resultMap="deptAndEmpResultMap">
select *
from t_dept
left join t_emp
on t_dept.dept_id = t_emp.dept_id
where t_dept.dept_id = #{deptId}
</select>
测试
@Test
public void testGetDeptAndEmpByDeptId(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
DeptMapper mapper = sqlSession.getMapper(DeptMapper.class);
Dept dept = mapper.getDeptAndEmpByDeptId(1);
System.out.println(dept);
}
![](https://img-blog.csdnimg.cn/0c3421d786844c2c90e0aedd875f04a4.png)