一. 准备
后面需要讲自定义映射,所以讲之前需要准备部门表_部门实体类_维护关系
二. 代码
创建表、添加外键、添加约束
-- 创建表
CREATE TABLE tbl_dept(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
dept_name VARCHAR(50)
);
--给员工表添加外键
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);
创建Department.java
package com.atguigu.mybatis.beans;
public class Department {
private Integer id;
private String department;
public Department() {
super();
// TODO Auto-generated constructor stub
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
@Override
public String toString() {
return "Department [id=" + id + ", department=" + department + "]";
}
}
在Employee.java中添加Department
package com.atguigu.mybatis.beans;
public class Employee {
private Integer id;
private String lastName;
private String email;
private String gender;
private Department dept;
public Employee() {
super();
// TODO Auto-generated constructor stub
}
public Employee(Integer id, String lastName, String email, String gender) {
super();
this.id = id;
this.lastName = lastName;
this.email = email;
this.gender = gender;
}
public Department getDept() {
return dept;
}
public void setDept(Department dept) {
this.dept = dept;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", gender=" + gender + "]";
}
}