在Mybatis中resultMap的用法(一)中已经介绍到了resultMap处理单张表的pojo封装用法,本文章将讲解基于两张表的多表查询。
resultMap可以实现将查询结果映射为复杂类型的pojo,比如在查询结果映射对象中包括pojo和list实现一对一查询和一对多查询。
1、一对一的查询
一对一数据模型:部门和员工
一名员工只会隶属于一个部门,所以从查询员工信息出发关联查询部门信息为一对一查询。如果从部门信息出发查询一个部门下的员工信息则为一对多查询,因为一个部门可以有多个员工。
- 添加部门信息的数据库表tb1_dept和与之对应的pojo类Dept:
@Data
public class Dept {
private Integer deptId;
private String deptName;
}
- 改造pojo类Emp
在员工类中添加Dept属性,Dept属性是一个引用类型,用于存储关联查询的部门信息,因为关联关系是一对一,所以只需要添加单个属性即可。
@Data
public class Emp {
private Integer empId;
private String empName;
private String gender;
private String email;
private Integer dId;
private Dept dept;
}
-
配置Mapper.xml配置文件empMapper.xml:
先使用id和result属性,映射Emp类的结果集,然后在使用association映射关联对象Dept的结果集。
<!-- 数据库有别名的,需要ResultMap封装成pojo-->
<resultMap id="emp" type="com.atguigu.boot.pojo.Emp">
<!-- id标签表示为主键属性-->
<id property="empId" column="emp_id"/>
<!-- property的属性为pojo的属性值,
与对应的是column的属性为emp表的-->
<result property="empName" column="emp_name"/>
<result property="gender" column="gender"/>
<result property="email" column="email"/>
<!-- 使用association封装Dept对象。javaType指定封装的对象类名-->
<association property="dept" javaType="com.atguigu.boot.pojo.Dept">
<id property="deptId" column="dept_id"/>
<result property="deptName" column="dept_name"/>
</association>
- 测试
@Controller
public class EmpController {
@Autowired
EmpService empService;
@GetMapping("/emp")
@ResponseBody
public List<Emp> getEmp(){
return empService.getEmp();
}
}
- 结果
2、一对多查询
查询所有部门信息及其部门下的员工信息。
-
修改pojo类Dept,添加员工集合属性
@Data
public class Dept {
private Integer deptId;
private String deptName;
private List<Emp> emps; //员工集合属性,存放员工信息
}
-
修改deptMapper.xml配置文件
使用id和result配置映射Dept类的结果,然后使用一对多关系的collection标签配置Emp结果。
<mapper namespace="com.atguigu.boot.mapper.DeptMapper">
<!-- type指定封装Dept类的属性-->
<resultMap id="dept" type="com.atguigu.boot.pojo.Dept">
<id property="deptId" column="dept_id"/>
<result property="deptName" column="dept_name"/>
<!-- property表示Dept类中的emps属性,
javaType指定属性值的类型
ofType表示集合中存储的是Emp对象-->
<collection property="emps" ofType="com.atguigu.boot.pojo.Emp" javaType="list">
<!-- id标签表示为主键属性-->
<id property="empId" column="emp_id"/>
<result property="empName" column="emp_name"/>
<result property="gender" column="gender"/>
<result property="email" column="email"/>
<result property="dId" column="d_id"/>
</collection>
</resultMap>
<select id="getDept" resultMap="dept">
select * from tb1_dept dept left outer join tb1_emp emp on dept.dept_id=emp.d_id
</select>
</mapper>
- 测试
@Controller
public class DeptController {
@Autowired
DeptService service;
@GetMapping("/dept")
@ResponseBody
public List<Dept> getDept(){
return service.getDept();
}
}
- 结果