场景重现
当想要查询一个部门下的所有员工时,多个员工 对应一个部门
实验使用的类和对象
mapper.xml
:
xml
<select id="getEmpAndDept" resultMap="empAndDeptResultMapTwo">
select * from t_emp
left join t_dept on t_emp.did = t_dept.did
where t_emp.eid = #{eid}
</select>
pojo
:
java
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Emp {
private Integer eid;
private String empName;
private Integer age;
private String sex;
private String email;
private Dept dept;
}
java
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Dept {
private Integer did;
private String deptName;
}
在 <result>
中直接使用 类.属性
来代表嵌套的pojo
xml
<resultMap id="empAndDeptResultMapOne" type="Emp">
<!--id设置主键属性,result设置普通属性-->
<id property="eid" column="eid"/>
<result property="empName" column="emp_name"/>
<result property="age" column="age"/>
<result property="sex" column="sex"/>
<result property="email" column="email"/>
<result property="dept.did" column="did"/>
<result property="dept.deptName" column="dept_name"/>
</resultMap
使用类.属性解决
在 <result>
中直接使用 类.属性
来代表嵌套的pojo
xml
<resultMap id="empAndDeptResultMapOne" type="Emp">
<!--id设置主键属性,result设置普通属性-->
<id property="eid" column="eid"/>
<result property="empName" column="emp_name"/>
<result property="age" column="age"/>
<result property="sex" column="sex"/>
<result property="email" column="email"/>
<result property="dept.did" column="did"/>
<result property="dept.deptName" column="dept_name"/>
</resultMap
使用<association> 解决
xml
<resultMap id="empAndDeptResultMapTwo" type="Emp">
<!--id设置主键属性,result设置普通属性-->
<id property="eid" column="eid"/>
<result property="empName" column="emp_name"/>
<result property="age" column="age"/>
<result property="sex" column="sex"/>
<result property="email" column="email"/>
<association property="dept" javaType="dept">
<id property="did" column="did"/>
<result property="deptName" column="dept_name"/>
</association>
</resultMap>
分布查询 解决
1. 分别在两个表对应的mapper,使用能关联的字段进行查询
java
Emp getEmpAndDeptByStepOne(Integer eid);
xml
<select id="getEmpAndDeptByStepOne">
select *
from t_emp
left join t_dept on t_emp.did = t_dept.did
where t_emp.eid = #{eid}
</select>
java
Dept getEmpAndDeptByStepTwo(Integer did);
xml
<select id="getEmpAndDeptByStepTwo" resultType="com.zxb.mybatis.pojo.Dept">
select * from t_dept where did = #{did}
</select>
2. 在主表的映射文件中,添加<association>字段,并用该字段查询子表
xml
<resultMap id="empAndDeptByStepResultMap" type="Emp">
<!--id设置主键属性,result设置普通属性-->
<id property="eid" column="eid"/>
<result property="empName" column="emp_name"/>
<result property="age" column="age"/>
<result property="sex" column="sex"/>
<result property="email" column="email"/>
<association property="dept" select="com.zxb.mybatis.mapper.DeptMapper.getEmpAndDeptByStepTwo" column="did"/>
</resultMap>
xml
<select id="getEmpAndDeptByStepOne" resultMap="empAndDeptByStepResultMap">
select *
from t_emp
left join t_dept on t_emp.did = t_dept.did
where t_emp.eid = #{eid}
</select>