假设我们想在查询Employee
的同时查询员工对应的部门,就是一个Employee
对应一个Department
,一个员工有与之对应的部门信息;
我们在Employee.java
中添加部门属性:
private Department dept;
public Department getDept() {
return dept;
}
public void setDept(Department dept) {
this.dept = dept;
}
然后我们去创建一个部门类(Department.java
):
package com.atguigu.mybatis.bean;
import java.util.List;
public class Department {
private Integer id;
private String departmentName;
public void setId(Integer id) {
this.id = id;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public Integer getId() {
return id;
}
public String getDepartmentName() {
return departmentName;
}
@Override
public String toString() {
return "Department [id=" + id + ", departmentName=" + departmentName
+ "]";
}
}
然后到数据库中创建一张部门表:
CREATE TABLE tbl_dept(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
dept_name VARCHAR(255)
)
然后添加两个部门:
然后为tbl_employee
添加部门信息,并且添加外键约束:
ALTER TABLE tbl_employee ADD COLUMN d_id INT(11);
ALTER TABLE tbl_employee ADD CONSTRAINT fk_emp_dept FOREIGN KEY(d_id) REFERENCES tbl_dept(id);
可以看到执行完后tbl_employee
表多了一列,然后我们为这一列赋上值就可以了:
这样我们的环境就搭好了!
接下来我们可以到接口中写方法了:
到EmployeeMapperPlus.java
接口中写:
public Employee getEmpAndDept(Integer id);
然后到EmployeeMapperPlus.xml
中实现方法:
<!-- public Employee getEmpAndDept(Integer id);-->
<select id="getEmpAndDept" resultMap="MyDifEmp">
SELECT e.id id,e.last_name last_name,e.gender gender,e.d_id d_id,
d.id did,d.dept_name dept_name FROM tbl_employee e,tbl_dept d
WHERE e.d_id=d.id AND e.id=#{id}
</select>
- 然后用
resultMap
把结果集封装起来,有两种封装方法: - 第一种:级联属性封装结果集
<!--
联合查询:级联属性封装结果集
-->
<resultMap type="com.atguigu.mybatis.bean.Employee" id="MyDifEmp">
<id column="id" property="id"/>
<result column="last_name" property="lastName"/>
<result column="gender" property="gender"/>
<result column="did" property="dept.id"/>
<result column="dept_name" property="dept.departmentName"/>
</resultMap>
- 第二种:
association
定义关联对象封装规则
<!--
使用association定义关联的单个对象的封装规则;
-->
<resultMap type="com.atguigu.mybatis.bean.Employee" id="MyDifEmp2">
<id column="id" property="id"/>
<result column="last_name" property="lastName"/>
<result column="gender" property="gender"/>
<!-- association可以指定联合的javaBean对象
property="dept":指定哪个属性是联合的对象
javaType:指定这个属性对象的类型[不能省略]
注意一下下面的association内的id标签和上面的id的column中的值不能相同,不然会出现问题
因为这是代表列名的,如果相同就都表示同一列了
-->
<association property="dept" javaType="com.atguigu.mybatis.bean.Department">
<id column="did" property="id"/>
<result column="dept_name" property="departmentName"/>
</association>
</resultMap>