本篇文章以Employee(员工)和Role(角色)为例讲述多对多映射关系的配置。
第一步:建表(MySQL)
#员工表
CREATE TABLE employee (
ID INT(2) PRIMARY KEY AUTO_INCREMENT,
NAME CHAR(10) NOT NULL,
AGE INT(2) NOT NULL);
#角色表
CREATE TABLE role (
ID INT(2) PRIMARY KEY AUTO_INCREMENT,
NAME CHAR(10) NOT NULL);
#关系表
CREATE TABLE employee_role_table (
EMPLOYEE_ID INT(2),
ROLE_ID INT(2),
FOREIGN KEY(EMPLOYEE_ID) REFERENCES employee(ID),
FOREIGN KEY(ROLE_ID) REFERENCES role(ID));
第二步:编写实体类
//Employee.java
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private Integer age;
private Set<Role> roles = new HashSet<Role>();
public Employee(Integer id, String name, Integer age) {
super();
this.id = id;
this.name = name;
this.age= age;
}
public Employee() {
super();
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
//Role.java
public class Role implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private Set<Employee> employees = new HashSet<>();
public Role(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
public Role() {
super();
}
public Set<Employee> getEmployees() {
return employees;
}
public void setEmployees(Set<Employee> employees) {
this.employees = employees;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
第三步:实体类与数据表映射文件
<!-- Employee.hbm.xml -->
<hibernate-mapping package="com.aha.hibernate.entity">
<class name="Employee" table="employee">
<id name="id" column="ID">
<generator class="native"></generator>
</id>
<property name="name" column="NAME"></property>
<property name="age" column="AGE"></property>
<set name="roles" table="employee_role_table ">
<!-- 此处应填写关系表中的字段名 -->
<key column="EMPLOYEE_ID"></key>
<!-- 此处应填写关系表中的字段名 -->
<many-to-many class="com.aha.hibernate.entity.Role" column="ROLE_ID"></many-to-many>
</set>
</class>
</hibernate-mapping>
<!-- Role.hbm.xml -->
<hibernate-mapping package="com.aha.hibernate.entity">
<class name="Role" table="role">
<id name="id" column="ID">
<generator class="native"></generator>
</id>
<property name="name" column="NAME"></property>
<!--
多对多映射不允许双方都对其进行维护,必须一方放弃维护,即inverse="true"
根据实际业务选择哪一方放弃维护,员工-角色应选择角色放弃维护。
-->
<set name="employees" table="employee_role_table" inverse="true">
<!-- 此处应填写关系表中的字段名 -->
<key column="ROLE_ID"></key>
<!-- 此处应填写关系表中的字段名 -->
<many-to-many class="com.aha.hibernate.entity.Employee" column="EMPLOYEE_ID"></many-to-many>
</set>
</class>
</hibernate-mapping>