Hibernate Many-to-many Mappings

Source: Internet
Author: User



To create a table:

CREATE TABLE EMPLOYEE (   ID INT not NULL auto_increment,   first_name VARCHAR () default NULL,   last_name  VARCHAR () default NULL,   salary     INT  default NULL,   PRIMARY KEY (ID)); CREATE table CERTIFICATE (   ID INT NOT NULL auto_increment,   certificate_name VARCHAR (+) default NULL,   PRIMARY KEY (id));

Intermediate table:

CREATE TABLE Emp_cert (   employee_id int not NULL,   certificate_id int not null,   PRIMARY KEY (employee_id,ce rtificate_id));



POJO class:

Package Com.jiangge.hblearn;import java.util.*;p ublic class employee{private int id;private String firstname;private String lastname;private int salary;private <span style= "color: #ff0000;" >set certificates</span>;p ublic employee () {}public employee (string fname, string lname, int salary) { This.firstname = Fname;this.lastname = Lname;this.salary = salary;} public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String Getfirstname () {return firstName;} public void Setfirstname (String first_name) {this.firstname = first_name;} Public String Getlastname () {return lastName;} public void Setlastname (String last_name) {this.lastname = last_name;} public int getsalary () {return salary;} public void setsalary (int salary) {this.salary = salary;} Public Set getcertificates () {return certificates;} public void Setcertificates (Set certificates) {this.certificates = certificates;}}


Package Com.jiangge.hblearn;public class Certificate{private int id;private String name;public Certificate () {}public Certificate (String name) {this.name = name;} public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public boolean equals (Object obj) {if (obj = = null) return False;if (!this.getclass (). Equals (Obj.getclass ())) return False ; Certificate obj2 = (Certificate) obj;if ((this.id = Obj2.getid ()) && (This.name.equals (Obj2.getname ()))) { return true;} return false;} public int hashcode () {int tmp = 0;TMP = (id + name). Hashcode (); return tmp;}}

Configuration file:

<?xml version= "1.0" encoding= "Utf-8"? ><! DOCTYPE hibernate-configuration SYSTEM "Http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd" >< Hibernate-configuration><session-factory><property name= "Hibernate.dialect" > Org.hibernate.dialect.mysqldialect</property><property name= "Hibernate.connection.driver_class" > com.mysql.jdbc.driver</property><!--assume Testone is the database name--><property name= " Hibernate.connection.url ">jdbc:mysql://localhost/testmany2many</property><property name=" Hibernate.connection.username ">root</property><property name=" Hibernate.connection.password "> Root</property><property name= "Hibernate.show_sql" >true</property><!--List of XML mapping Files--><mapping resource= "Resource/employee.hbm.xml"/></session-factory></ Hibernate-configuration>


Mapping file (written to a file Employee.hbm.xml):

<?xml version= "1.0" encoding= "Utf-8"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping dtd//en" "http://www.hibernate.org/dtd/ Hibernate-mapping-3.0.dtd > <!--Many-to-many relationship mappings: The <set> element sets the relationship between Certificate and Empl Oyee classes. We set Cascade attribute to Save-update to tell Hibernate to persist the Certificate objects for Save i.e. CREATE and UPDA TE operations at the same time as the Employee objects. The name attribute is set to the defined set variable in the parent class and in our case it is certificates. For each set variable, we need to define a separate set element in the mapping file. Here we used name attribute to set the intermediate table name to Emp_cert. The <key> element is the column in the Emp_cert table, holds the foreign key to the parent object ie. Table EMPLOYEE and links to the certification_id in the CERTIFICATE table. The <many-to-many> element indicates that one Employee object relates to MAny Certificate objects and column attributes is used to link intermediate emp_cert.-->


Test:

Package Test;import Java.util.*;import Org.hibernate.hibernateexception;import org.hibernate.session;import Org.hibernate.transaction;import Org.hibernate.sessionfactory;import Org.hibernate.cfg.configuration;import Com.jiangge.hblearn.certificate;import Com.jiangge.hblearn.employee;public class Manageemployee{private static Sessionfactory factory;public static void Main (string[] args) {try{factory = new Configuration (). Configure (). Buildsessionfactory ();} catch (Throwable ex) {System.err.println ("Failed to create Sessionfactory object." + ex); throw new Exceptionininitializererror (ex);} Manageemployee ME = new Manageemployee ();/* Let us had a set of certificates for the first employee */hashset certificate s = new HashSet (); Certificates.add (New Certificate ("MCA")); Certificates.add (New Certificate ("MBA")); Certificates.add (New Certificate ("PMP"));/* Add employee records in the database */integer empID1 = Me.addemployee ("Manoj "," Kumar ", 4000, certificates);/* ADD another employee record in THe database */integer empID2 = Me.addemployee ("Dilip", "Kumar", +, certificates);/* List down all the employees */me.li Stemployees ();/* Update employee ' s salary Records */me.updateemployee (empID1,);/* Delete an employee from the Databas E */me.deleteemployee (empID2);/* List down all the Employees */me.listemployees ();} /* Method to add a employee record in the database */public Integer addemployee (String fname, string lname, int salary, S ET cert) {Session session = Factory.opensession (); Transaction tx = Null;integer EmployeeID = NULL;TRY{TX = Session.begintransaction (); Employee Employee = new Employee (fname, lname, salary); employee.setcertificates (cert); EmployeeID = (Integer) Session.save (employee); Tx.commit ();} catch (Hibernateexception e) {if (tx! = null) Tx.rollback (); E.printstacktrace ();} Finally{session.close ();} return EmployeeID;} /* Method to list all the employees detail */public void Listemployees () {Session session = Factory.opensession (); Transaction tx = NULL;TRY{TX = SessioN.begintransaction (); List employees = Session.createquery ("from Employee"). List (), for (Iterator Iterator1 = Employees.iterator (); Iterator1.hasnext ();) {Employee employee = (employee) iterator1.next (); System.out.print ("First Name:" + employee.getfirstname ()); System.out.print ("Last Name:" + employee.getlastname ()); System.out.println ("Salary:" + employee.getsalary ()); Set certificates = Employee.getcertificates (); for (Iterator Iterator2 = Certificates.iterator (); Iterator2.hasnext ();) {Certificate CertName = (Certificate) iterator2.next (); System.out.println ("Certificate:" + certname.getname ());}} Tx.commit ();} catch (Hibernateexception e) {if (tx! = null) Tx.rollback (); E.printstacktrace ();} Finally{session.close ();}} /* Method to update salary-an employee */public void UpdateEmployee (Integer EmployeeID, int salary) {Session session = Factory.opensession (); Transaction tx = NULL;TRY{TX = Session.begintransaction (); Employee employee = (employee) session.get (Employee.class,employeeid); EMPLoyee.setsalary (Salary); Session.update (employee); Tx.commit ();} catch (Hibernateexception e) {if (tx! = null) Tx.rollback (); E.printstacktrace ();} Finally{session.close ();}} /* Method to delete a employee from the records */public void Deleteemployee (Integer EmployeeID) {Session session = Factor Y.opensession (); Transaction tx = NULL;TRY{TX = Session.begintransaction (); Employee employee = (employee) session.get (Employee.class,employeeid); Session.delete (employee); Tx.commit ();} catch (Hibernateexception e) {if (tx! = null) Tx.rollback (); E.printstacktrace ();} finally{session.close ();}}}



Database results:

Mysql> SELECT * from employee;+----+------------+-----------+--------+| ID | first_name | last_name | Salary |+----+------------+-----------+--------+| 22 | Manoj      | Kumar     |   |+----+------------+-----------+--------+1 row in Set (0.00 sec) mysql> SELECT * from certificate;+----+--------- ---------+| ID | Certificate_name |+----+------------------+|  4 | MBA              | |  5 | PMP              | |  6 | MCA              |+----+------------------+3 rows in Set (0.00 sec) mysql> Select * from emp_cert;+-------------+------------- ---+| employee_id | certificate_id |+-------------+----------------+|          |              4 | |          |              5 | |          |              6 |+-------------+----------------+3 rows in Set (0.00 sec) mysql>






Hibernate Many-to-many Mappings

Related Article

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.