例如:员工与部门的关系,多对一映射,当查询员工时同时查出所属部门;
Emp中的dept字段为引用类型;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Emp {
// 员工编号
private Integer empId;
// 员工名称
private String empName;
// 部门ID
private Integer deptId;
// 员工部门
private Dept dept;
}
mybatis中处理多对一映射关系的三种方法:
1、级联方式
<resultMap id="empAndDeptMap" type="Emp">
<result property="empId" column="emp_id"/>
<result property="empName" column="emp_name"/>
<!--级联映射-->
<result property="dept.deptId" column="dept_id"/>
<result property="dept.deptName" column="dept_Name"/>
</resultMap>
<select id="queryEmpAndDeptById" resultMap="empAndDeptMap">
select emp_id,
emp_name,
E.dept_id,
dept_name
from EMP E LEFT JOIN DEPT D ON D.dept_id = E.dept_id
where emp_id =${empId}
</select>
2、association
<resultMap id="empAndDeptMapOne" type="Emp">
<result property="empId" column="emp_id"/>
<result property="empName" column="emp_name"/>
<!--association-->
<association property="dept" javaType="Dept">
<id column="dept_id" property="deptId"/>
<result column="dept_name" property="deptName"/>
</association>
</resultMap>
<select id="queryEmpAndDeptById" resultMap="empAndDeptMap">
select emp_id,
emp_name,
E.dept_id,
dept_name
from EMP E LEFT JOIN DEPT D ON D.dept_id = E.dept_id
where emp_id =${empId}
</select>
3、分步查询
<resultMap id="empAndDeptStepMap" type="Emp">
<result property="empId" column="emp_id"/>
<result property="empName" column="emp_name"/>
<!--association-->
<association property="dept"
select="com.neusoft.mybatis.parameter.mapper.DeptMapper.queryDeptById"
column="dept_id"/>
</resultMap>
<select id="queryEmpAndDeptById" resultMap="empAndDeptStepMap">
select emp_id,
emp_name,
dept_id
from EMP E
where emp_id =${empId}
</select>
查询结果如下:
Emp(empId=1, empName=某某, deptId=null, dept=Dept(deptId=1, deptName=解决方案))