Many-to-many bidirectional correlation (Project (Project)/emp (employee) as a case):
The steps are as follows:
1. Create the project class and need to define the EMP properties of the collection type
public class Project { //number private Integer pid; Name private String pname; Defines the EMP attribute of the collection type private set<emp> emps=new hashset<emp> (); Public Integer Getpid () { return pid; } public void Setpid (Integer pid) { this.pid = pid; } Public String Getpname () { return pname; } public void Setpname (String pname) { this.pname = pname; } Public set<emp> Getemps () { return emps; } public void Setemps (set<emp> emps) { this.emps = emps; }
2. Create an EMP class and need to define the project properties of the collection type
public class Emp { private String empname; Private Integer nid; Private set<project> pros=new hashset<project> (); Public String Getempname () { return empname; } public void Setempname (String empname) { this.empname = empname; } Public Integer Getnid () { return nid; } public void Setnid (Integer nid) { this.nid = nid; } Public set<project> Getpros () { return pros; } public void Setpros (set<project> pros) { This.pros = pros; } }
3. Note : need to establish a third table associated with project and EMP respective primary key PID, nid
The implementation of many-to-many association relationships requires a connection table,<set> property indicates the name of the join table,<key> the field name of the foreign key that refers to the project table ID of the connection table;<many-to-many> Class that specifies a many-to-many association with the EMP, column specifies the field name of the foreign key that joins the table reference to the EMP mapping table (where the Emp.hbm.xml is mapped to an EMP table) ID.
4, write Project.hbm.xml and Emp.hbm.xml small configuration, and implant the table property in the <set> element the third table proemp and many-to-many <many-to-many> tag class specified type
Emp.hbm.xml key code is as follows:
Project.hbm.xml key code is as follows:
5, large configuration hibernate.cfg.xml need to be associated with small configuration
<mapping resource= "Cn/happy/manytomany/project.hbm.xml"/><mapping resource= "cn/happy/manytomany/ Emp.hbm.xml "/>
6. Test class Tests
/* Many-to-many bidirectional * /@Test public void Addtest () { //Create an Employee object EMP emp=new emp (); Emp.setempname ("Unknown"); Create Project Object Project pro=new project (); Pro.setpname ("garden"); Add an Employee object to the project conversely pro.getemps (). Add (EMP); Emp.getpros (). Add (pro); Save Session.save (pro); Session.save (EMP); }
Note: for bidirectional Many-to-many associations, you need to set one end of the inverse property to True, otherwise the constraint is violated.
Hibernate mapping Many-to-many bidirectional relationships (small case)