MyBatis中处理多对一的映射关系
1.级联方式处理
关键:明白字段应该映射哪一个属性
也就是将主表中主键为id,关联表中的要查询的值通过column对应数据库中名字,property对应实体类中的名字进行映射
<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>
2.association标签
模板
<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>
3.分步查询
先查询出一个表中的数据
再利用该表中数据的某个元素在第二个表中查询数据
(注意,一般该方法的两个步骤写在在不同的接口中
因为他们对应的是不同的实体类,返回值不同)
优点:可以实现延迟加载,减少当前内存的消耗
<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>
<!--
property:设置需要处理映射关系的属性的属性名
select:设置分布查询的sql的唯一标识
(在对应接口中找到对应方法通过右键选copy Reference复制
或按ctrl+shift+alt+C复制)
column:将查询处的某个字段作为分布查询的sql的条件
fetchType:在开启了延迟加载的环境中,通过该属性
来实现需要延迟加载还是立即加载(全部加载)
fetchType:eager(立即加载,全部加载)/lazy(延迟加载)
-->
<association property="dept" fetchType="eager"
select="com.javasm.mybatis.mapper.DeptMapper.getEmpAndDeptByStepTwo"
column="dept_id"></association>