一对多与多对一的区别:
以部门表为单位,一个部门会有很多员工为一对多的关系
以员工表为单位,会有多个员工在一个部门中为多对一的关系
一:collection
由于一个部门中会有多个员工,即一对多的关系因此我们需要的实体类Dept中存在一个集合属性,里面存放的数据类型为员工类型来存储多个员工
在resultMap中的映射关系为:
<resultMap id="deptAndEmpResultMap" type="Dept">
<id property="did" column="did"></id>
<result property="deptName" column="dept_name"></result>
<!--
collection 用来处理一对多的映射关系
ofType:表示该属性对应的集合中的存储数据的类型
-->
<collection property="emps" ofType="Emp">
<id property="eid" column="eid"></id>
<result property="empName" column="emp_name"></result>
<result property="age" column="age"></result>
<result property="sex" column="sex"></result>
<result property="email" column="email"></result>
</collection>
</resultMap>
<!--Dept getDeptAndEmp(@Param("did") Integer did);-->
<select id="getDeptAndEmp" resultMap="deptAndEmpResultMap">
select * from t_dept left join t_emp on t_dept.did = t_emp.did where t_dept.did = #{did}
</select>
这里使用了ofType,与之前多对一查询中不同的是ofType表示这个集合中存放的数据类型
而
中javaType表示多对一关系中的属性类型。两个场景不同的方法罢了
二、分步查询
第一步:查询部门信息
<!--Dept getDeptAndEmpByStepOne(@Param("did") Integer did);-->
<select id="getDeptAndEmpByStepOne" resultMap="deptAndEmpByStepOne">
select * from t_dept where did = #{did}
</select>
通过查询到的部门信息中的did,来在员工表中查找对应的员工信息
因此,在resultMap中
<resultMap id="deptAndEmpByStepOne" type="Dept">
<id property="did" column="did"></id>
<result property="deptName" column="dept_name"></result>
<collection property="emps"
select="mybatis.mapper.EmpMapper.getDeptAndEmpByStepTwo"
column="did">
</collection>
</resultMap>
需要指定第二步的sql语句的唯一标识以及查询的条件column did
<!--List<Emp> getDeptAndEmpByStepTwo(@Param("did") Integer did);-->
<select id="getDeptAndEmpByStepTwo" resultType="Emp">
select * from t_emp where did = #{did}
</select>