Hibernate的双向多对多关联有两种配置方法:那我们就来看看两种方案是如何配置的。
一、创建以各自类为类型的集合来关联
1.首先我们要在两个实体类(雇员<Emploee>、工程<Project>)中各自给对方添加一个对方的集合
1.1 雇员实体类
package cn.manytomany.one;
import java.util.HashSet;
import java.util.Set;
public class Emploee {
//雇员id
private Integer empId;
//工程
private String empName;
//工程的集合
private Set<Project> projects=new HashSet<Project>();
public Set<Project> getProjects() {
return projects;
}
public void setProjects(Set<Project> projects) {
this.projects = projects;
}
public Integer getEmpId() {
return empId;
}
public void setEmpId(Integer empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
}
1.2 工程实体类
package cn.manytomany.one;
import java.util.HashSet;
import java.util.Set;
public class Project {
private Integer proId;
private String proName;
private Set<Emploee> emploees=new HashSet<Emploee>();
public Set<Emploee> getEmploees() {
return emploees;
}
public void setEmploees(Set<Emploee> emploees) {
this.emploees = emploees;
}
public Integer getProId() {
return proId;
}
public void setProId(Integer proId) {
this.proId = proId;
}
public String getProName() {
return proName;
}
public void setProName(String proName) {
this.proName = proName;
}
}
2.有了实体类之后呢,我们就能通过实体的属性和数据库的表字段配置映射关系。
2.1 emploees.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.manytomany.one">
<class table="Emploee">
<id>
<generator>
<param>SQU_NUM</param>
</generator>
</id>
<property></property>
<set table="PROEMP">
<key column="RPROID"></key>
<many-to-many column="REMPID">
</many-to-many>
</set>
</class>
</hibernate-mapping>
2.2 projects.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.manytomany.one">
<class table="PROJECT">
<id>
<generator>
<param>SQU_NUM</param>
</generator>
</id>
<property></property>
<set table="PROEMP" cascade="save-update">
<key column="REMPID"></key>
<many-to-many column="RPROID">
</many-to-many>
</set>
</class>
</hibernate-mapping>
2.3 另外还有一个最重要的大配置来引用两个小配置
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>