MyBatis使用resultMap自定义映射处理多对一的映射关系的三种方法
1.级联方式处理
2.association标签
3.分步查询
这里是基于t_emp,t_dept员工信息表与部门信息表对应的mapper接口实现方法,在员工信息表中有部门信息id这一字段,而在部门信息表中id字段与部门名称字段是一 一对应的。所以员工信息与部门信息是多对一的关系(多个员工可能在一个部门)
1.级联方式处理
//获取员工及对应部门信息
Emp getEmpAndDeptByEmpId(@Param("empId") Integer empId);
<resultMap id="empAndDeptResultMapOne" type="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>
<result column="dept_id" property="dept.deptId"></result>
<result column="dept_name" property="dept.deptName"></result>
</resultMap>
<select id="getEmpAndDeptByEmpId" resultMap="empAndDeptResultMap">
select t_emp.*,t_dept.* from t_emp left join t_dept on t_emp.dept_id=t_dept.dept_id where t_emp.emp_id=#{empId}
</select>
2.使用association标签
//获取员工及对应部门信息
Emp getEmpAndDeptByEmpId(@Param("empId") Integer empId);
<resultMap id="empAndDeptResultMap" type="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>
//association:处理多对一的映射关系(也就是处理实体类类型的属性)
//-property:设置需要处理映射关系的属性的属性名
//-javaType:设置要处理的属性的类型
<association property="dept" javaType="Dept">
<id column="dept_id" property="deptId"></id>
<result column="dept_name" property="deptName"></result>
</association>
</resultMap>
<select id="getEmpAndDeptByEmpId" resultMap="empAndDeptResultMap">
select t_emp.*,t_dept.* from t_emp left join t_dept on t_emp.dept_id=t_dept.dept_id where t_emp.emp_id=#{empId}
</select>
3.分步查询
分布查询就是EmpMapper中先对t_emp做第一步查询,查询出的员工信息表字段的全部属性其中就包括部门信息表中的id,然后再基于这个id通过DempMapper查询部门信息表中的字段属性,再把查询出的部门信息表的数据放到resultMap中,最后就能得到两表联查的结果
//通过分布查询查询员工以及所对应的部门信息的第一步
Emp getEmpAndDeptByEmpStepOne(@Param("empId") Integer empId);
<resultMap id="empAndDeptByStepResultMap" type="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>
<association property="dept"
select="com.qcw.mybatis.mapper.DeptMapper.getEmpAndDeptByStepTwo"
column="dept_id"></association>
</resultMap>
<select id="getEmpAndDeptByEmpStepOne" resultMap="empAndDeptByStepResultMap">
select * from t_emp where emp_id = #{empId}
</select>
//通过分布查询查询员工以及所对应的部门信息的第二步
Dept getEmpAndDeptByStepTwo(@Param("deptId") Integer deptId);
<select id="getEmpAndDeptByStepTwo" resultType="Dept">
select * from t_dept where dept_id = #{deptId}
</select>
最后这里附上测试方法:
@Test
public void getEmpAndDeptByEmpStepTest(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
Emp emp = mapper.getEmpAndDeptByEmpStepOne(2);
System.out.println("emp = " + emp);
}