Bidirectional many-to-many relationship mapping of hibernate framework

Source: Internet
Author: User
Tags configuration settings

Yesterday, we shared a one -way, one-way, one- to - Many mapping relationship in Hibernate, and today we share the many-to-many mappings in hibernate in two directions .

This time we take the project and the staff to raise a chestnut, because you can imagine, in the real environment, a project must be corresponding to a number of employees, which undoubtedly,

At the same time, a comparison of cattle employees can also participate in the development of multiple projects, which reflects the two-way many-to-many relationship.

First of all, we need to figure out the relationship between tables and tables in the underlying database, we create an employee table (employee) and a project table (project) without a doubt, how do we show the many-to-many relationship?

Of course there are a number of ways, here I would like to put a separate table for example, that is, I create a separate table to save the relationship between employees and projects, the specific entity classes are as follows

Employee

Package entity;import Java.util.hashset;import java.util.Set;/** Employee Table **/ Public classEmployee {PrivateInteger Empid;//Employee Number    PrivateString EmpName;//Employee Name//prepare a project collection    PrivateSet<project> pros=NewHashset<project>();  PublicSet<project>Getpros () {returnPros; }     Public voidSetpros (set<project>pros) {         This. Pros =Pros; }             PublicEmployee (String empname) {super ();  This. EmpName =EmpName; }     PublicEmployee (Integer empid, String empname) { This. Empid =Empid;  This. EmpName =EmpName; }     PublicEmployee () {} PublicInteger getempid () {returnEmpid; }     Public voidsetempid (Integer empid) { This. Empid =Empid; }     PublicString Getempname () {returnEmpName; }     Public voidsetempname (String empname) { This. EmpName =EmpName; }    }

Proemp

Package entity;/** represents an employee and project associated table **/ Public classProemp {PrivateInteger rproid;//Project Number    PrivateInteger Rempid;//Employee Number             Publicproemp (integer rproid, integer rempid) { This. rproid =rproid;  This. Rempid =Rempid; }     Publicproemp () {} PublicInteger getrproid () {returnrproid; }     Public voidsetrproid (Integer rproid) { This. rproid =rproid; }     PublicInteger getrempid () {returnRempid; }     Public voidsetrempid (Integer rempid) { This. Rempid =Rempid; }    }

Project

Package entity;import Java.util.hashset;import java.util.Set;/** Project Table **/ Public classProject {PrivateInteger proid;//Project Number    PrivateString Proname;//Project Name//declaring an employee collection    PrivateSet<employee> emps=NewHashset<employee>();  PublicSet<employee>Getemps () {returnEmps; }     Public voidSetemps (set<employee>emps) {         This. Emps =Emps; }             PublicProject (String proname) { This. Proname =Proname; }     PublicInteger getproid () {returnproid; }     Public voidsetproid (Integer proid) { This. proid =proid; }     PublicString Getproname () {returnProname; }     Public voidsetproname (String proname) { This. Proname =Proname; }     PublicProject (Integer proid, String proname) { This. proid =proid;  This. Proname =Proname; }     PublicProject () {}}

So that our entity classes are all created, and then we can configure the mapping relationship file, since it is a two-way multi-to-many relationship, then must be <set></set> tags

Project.hbm.xml

<?xml version="1.0"? ><! DOCTYPE hibernate-Mapping Public"-//hibernate/hibernate Mapping DTD 3.0//en"        "HTTP://WWW.HIBERNATE.ORG/DTD/HIBERNATE-MAPPING-3.0.DTD">"Entity"> <className="Project"table="Project"> <id name="proid"column="proid"> <generatorclass="Increment"/> </id> <property name="Proname"Type="string"column="Proname"/> <!--Configure many-to-many associations set cascading properties--<SetName="Emps"table="proemp"Cascade=" All"> <key column="rproid"></key> <many-to-manyclass="entity. Employee"column="Rempid"></many-to-many> </Set> </class>

Employee.hbm.xml

<?xml version="1.0"? ><! DOCTYPE hibernate-Mapping Public"-//hibernate/hibernate Mapping DTD 3.0//en"        "HTTP://WWW.HIBERNATE.ORG/DTD/HIBERNATE-MAPPING-3.0.DTD">"Entity"> <className="Employee"table="Employee"> <id name="Empid"column="Empid"> <generatorclass="Increment"/> </id> <property name="EmpName"Type="string"column="EmpName"/> <!--Configure many-to-many association configuration settings invert properties, let project management relationship--<SetName="Pros"table="proemp"Inverse="true"> <key column="Rempid"></key> <many-to-manyclass="entity. Project"column="rproid"></many-to-many> </Set> </class>

After the above steps, the entire configuration process is complete, of course, students do not forget to add a two mapping files (small configuration) in the Hibernate configuration file (large configuration) reference

Test class

Package test;import org.hibernate.session;import org.hibernate.transaction;import util. Hibernateutil;import entity. Employee;import entity. Project; Public classTest { Public Static voidMain (string[] args) {/** Many-to-many affinity configurations * Configure a many-to-many association relationship between project and employee in both directions * Association is maintained by project party and cascading properties are set on project side * */        //Get SessionSession session=hibernateutil.currentsession (); //Open TransactionTransaction tx =session.begintransaction (); //build two projectsProject pro1=NewProject ("Project One"); Project Pro2=NewProject ("Item Two"); //Build multiple EmployeesEmployee emp1=NewEmployee ("the rainy season in Paris"); Employee EMP2=NewEmployee ("the fruit of summer"); Employee Emp3=NewEmployee ("Listen to the Wind"); Employee Emp4=NewEmployee ("The Darkness before the Dawn"); //Add employee 123 to project onepro1.getemps (). Add (EMP1);        Pro1.getemps (). Add (EMP2);        Pro1.getemps (). Add (Emp3); //Add employee 234 to project twopro2.getemps (). Add (EMP2);        Pro2.getemps (). Add (Emp3);                Pro2.getemps (). Add (Emp4); //Save Project I and project twoSession.save (Pro1);        Session.save (PRO2); //Commit a transactionTx.commit (); //Close Connectionhibernateutil.closesession (); }}

The above code, we can find that we just saved the project, and did not manually add to save the employee's code, nor manually add the table to save the relationship between employees and the project code

We can see the SQL that hibernate helped us generate

Hibernate is a smart configuration file that helps us generate the SQL we need, which is the embodiment of object-oriented thinking , and we've been focusing on the object of the project and doing what we need to do.

We can look at the records in the database.

The above is how to configure the bidirectional many-to-many mapping relationship code and interpretation. I hope to have a little use for everyone ~

Bidirectional many-to-many relationship mapping of hibernate framework

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.