职员表(t_emp):
| emp_id | emp_name | age | gender | dept_id |
|---|---|---|---|---|
| 1 | Tom | 10 | 男 | 1 |
| 2 | Jim | 20 | 女 | 1 |
| 3 | Sam | 30 | 男 | 1 |
| 4 | Oum | 27 | 男 | 2 |
| 5 | Kim | 14 | 女 | 3 |
| 6 | Yum | 36 | 男 | 3 |
部门表(t_dept):
| dept_id | dept_name |
|---|---|
| 1 | A |
| 2 | B |
| 3 | C |
POJO实体类:成员变量根据两张表创建
Emp:成员变量(Dept dept)、Getter、Setter、Constructor、toString
Dept:成员变量(List
1、当字段名和属性名不一致的情况,如何来处理映射关系
(1)为查询的字段设置别名,和属性名保持一致
select emp_id empId, emp_name empName, age, gender from t_emp where emp_id = #{empId}
(2)当字段符合MySQL的要求使用_,而属性符合java的要求使用驼峰
emp_id:empId emp_name:empName dept_id:deptId-->
(3)使用resultMap自定义映射来处理
select * from t_emp where emp_id = #{empId}
2、处理多对一的映射关系
public class Emp {
private Integer empId;
private String empName;
private Integer age;
private String gender;
//多个员工对应一个部门
private Dept dept; // N : 1
//...
}
(1)级联方式处理
(2)association方式
(3)分步查询:
优点:可以实现延时加载 注意事项:多对一的分步查询使用的是 association 标签
2、处理一对多的映射关系
public class Dept {
private Integer deptId;
private String deptName;
//一个部门对应多个员工
private List emps; //1 : N
//...
}
(1)Collection方式
SELECT * FROM t_dept LEFT JOIN t_emp ON t_dept.dept_id = t_emp.dept_id WHERe t_dept.dept_id = #{deptId}
(2)分步查询
注意事项:多对一使用分步查询使用的是 collection 标签
select * from t_dept where dept_id = #{deptId}
select * from t_emp where dept_id = #{deptId}



