问题描述:
数据库中有两张表——员工表和部门表,对应于两个实体类Employee和Department。由于每个员工必有一个部门,所以Employee中需要引用Department。
一开始想着MyBatis中要求实体类的属性和数据库表的字段对应,Employee里用的是Department的id,但这样会导致最后前端显示也只是显示部门id(后端如果再用id去查部门名也能实现,但比较麻烦了)。
后面改用Employee里直接用Department对象,然而不知道EmployeeMapper.xml该如何去写SQL,经过各种搜索找到了答案。
解决方法
先通过联表查询,查询出department表和employee表中所需信息,再通过别名,将department表中查出的字段名改为Department类的属性名。
实体类
Employee
package com.zcy.pojo;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@NoArgsConstructor
public class Employee {
private int id;
private String name;
private String email;
private int gender;//女0,男1
private Department department;
private Date birthday;
}
Department
package com.zcy.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Department {
private int id;//部门ID
private String name;//部门名称
}
MyBatis中的SQL
<select id="queryAllEmployee" resultType="employee">
select
a.id, a.name, a.email, a.gender,
b.id "department.id",
b.name "department.name",
birthday
from employee a
inner join department b
where a.department_id = b.id;
</select>
结果: