场景重现


当想要查询一个员工的所在部门,一个员工 对应一个部门

实验使用的类和对象

mapper.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:

@Data  
@AllArgsConstructor  
@NoArgsConstructor  
public class Emp {  
    private Integer eid;  
    private String empName;  
    private Integer age;  
    private String sex;  
    private String email;  
    private Dept dept;  
}
@Data  
@AllArgsConstructor  
@NoArgsConstructor  
public class Dept {  
    private Integer did;  
    private String deptName;  
}

使用类.属性解决


<result> 中直接使用 类.属性 来代表嵌套的pojo

<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> 解决

<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,使用能关联的字段进行查询

Emp getEmpAndDeptByStepOne(Integer eid);
<select id="getEmpAndDeptByStepOne">  
    select *  
    from t_emp             
    left join t_dept on t_emp.did = t_dept.did    
    where t_emp.eid = #{eid}
</select>
Dept getEmpAndDeptByStepTwo(Integer did);
<select id="getEmpAndDeptByStepTwo" resultType="com.zxb.mybatis.pojo.Dept">  
    select * from t_dept where did = #{did}  
</select>

2. 在主表的映射文件中,添加<association>字段,并用该字段查询子表

<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>
<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>