Hibernate One-to-many Mappings One-to-many relationship mapping

Source: Internet
Author: User

Hibernate One-to-many Mappings One-to-many relationship mapping


Key point: A one-to-many relationship uses the Set implementation,

Example: An employee can have more than one certificate of study.


steps to use Hibernate framework:
1. Create Hibernate configuration file (Hibernate.cfg.xml)
2. Create a persistence class, that is, the class whose instance needs to be saved to the database (Employee.java)
3. Create object-relational mapping file (Employee.hbm.xml)

4. Write code to access the database through the Hibernate API



Create Hibernate configuration file (Hibernate.cfg.xml)

<?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/testone2many</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>



2. Create a persistence class, that is, the class whose instance needs to be saved to the database (Employee.java)


Employee.java file:

Package Com.jiangge.hblearn;import java.util.set;public class employee{private int id;private String firstname;private string lastname;private int salary;private Set Certificates;public 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;}}



Certificate.java file:

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;}}



Create a table for the MySQL database:

Mysql> CREATE TABLE EMPLOYEE (   ID INT not NULL auto_increment,   first_name VARCHAR) default NULL,   last_n Ame  VARCHAR () default NULL,   salary     INT  default NULL,   PRIMARY KEY (id)); Query OK, 0 rows affectedmysql> create TABLE CERTIFICATE (   ID INT not NULL auto_increment,   certificate_name VAR CHAR (+) default NULL,   employee_id INT default NULL,   



Create object-relational Map file (Empoyee.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 "><!--the <set> element sets the relationship between Certificate and Employee Clas Ses. We used the Cascade attribute in the-<set> element to-tell Hibernate-persist the Certificate objects 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. The <key> element is the column in the CERTIFICATE table, holds the foreign key to the parent object ie. Table EMPLOYEE. The <one-to-many> element indicates this one Employee object relates to many Certificate objects. -->



Write code to access the database through the Hibernate API

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;/** * Test class: One-to-many relationships. An employee can have multiple diploma certificates * CRUD Operations * @author Jiangge * */public class Manageemployee{private static sessionfactory factory;public stat IC 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 has a set of certificates for the first employee */hashset Set1 = new HashSet (), Set1.add (New Certificate ("MCA")), Set1.add (New Certificate ("MBA")), Set1.add (New Certificate ("PMP"));/* ADD employee records in the database */integer empID1 = Me.addemployee ("Manoj", "Kumar", 4000, SET1);/* Another set of certificates for the second employee */hashset Set2 = new HashSet (); Set2.add (New Certificate ("BCA")); Set2.add (New Cert Ificate ("BA"));/* ADD Another employee record in the database */integer empID2 = Me.addemployee ("Dilip", "Kumar", +, SE T2);/* List down all the Employees */me.listemployees ();/* Update employee ' s salary Records */me.updateemployee (empID1, 50 */* Delete an employee from the database */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 ();}}}



Operation Result:

In the database:




IDE Console:

Log4j:warn No Appenders could is found for logger (org.hibernate.cfg.Environment). Log4j:warn Please initialize the log4j s Ystem properly. Hibernate:insert into EMPLOYEE (first_name, last_name, salary) VALUES (?,?,?) Hibernate:insert into CERTIFICATE (certificate_name) VALUES (?) Hibernate:insert into CERTIFICATE (certificate_name) VALUES (?) Hibernate:insert into CERTIFICATE (certificate_name) VALUES (?) Hibernate:update CERTIFICATE set employee_id=? where id=? Hibernate:update CERTIFICATE set employee_id=? where id=? Hibernate:update CERTIFICATE set employee_id=? where id=? Hibernate:insert into EMPLOYEE (first_name, last_name, salary) VALUES (?,?,?) Hibernate:insert into CERTIFICATE (certificate_name) VALUES (?) Hibernate:insert into CERTIFICATE (certificate_name) VALUES (?) Hibernate:update CERTIFICATE set employee_id=? where id=? Hibernate:update CERTIFICATE set employee_id=? where id=? Hibernate:select employee0_.id as id0_, employee0_.first_name as first2_0_, Employee0_.last_Name as last3_0_, employee0_.salary as salary0_ from EMPLOYEE employee0_first name:manoj last Name:kumar salary:4000h Ibernate:select certificat0_.employee_id as employee3_1_, certificat0_.id as id1_, certificat0_.id as id1_0_, Certificat 0_.certificate_name as certific2_1_0_ from certificate certificat0_ where certificat0_.employee_id=? Certificate:MBACertificate:MCACertificate:PMPFirst Name:dilip last Name:kumar salary:3000hibernate:select Certifi cat0_.employee_id as employee3_1_, certificat0_.id as id1_, certificat0_.id as id1_0_, Certificat0_.certificate_name as C ertific2_1_0_ from CERTIFICATE certificat0_ where certificat0_.employee_id=? Certificate:BACertificate:BCAHibernate:select employee0_.id as id0_0_, employee0_.first_name as first2_0_0_, Employee0_.last_name as last3_0_0_, employee0_.salary as salary0_0_ from EMPLOYEE employee0_ where employee0_.id=? Hibernate:update EMPLOYEE set first_name=?, Last_name=?, salary=? where id=? Hibernate:select Employee0_.id asid0_0_, Employee0_.first_name as first2_0_0_, employee0_.last_name as last3_0_0_, employee0_.salary as salary0_0_ from EM Ployee employee0_ where employee0_.id=? Hibernate:select certificat0_.employee_id as employee3_1_, certificat0_.id as id1_, certificat0_.id as id1_0_, Certifica T0_.certificate_name as certific2_1_0_ from certificate certificat0_ where certificat0_.employee_id=? Hibernate:update CERTIFICATE set employee_id=null where employee_id=? Hibernate:delete from CERTIFICATE where id=? Hibernate:delete from CERTIFICATE where id=? Hibernate:delete from EMPLOYEE where id=? Hibernate:select employee0_.id as id0_, employee0_.first_name as first2_0_, employee0_.last_name as last3_0_, employee0_ . Salary as salary0_ from EMPLOYEE employee0_first name:manoj last Name:kumar salary:5000hibernate:select certificat0 _.employee_id as employee3_1_, certificat0_.id as id1_, certificat0_.id as id1_0_, certificat0_.certificate_name as Certi fic2_1_0_ from CERTIFICATE certificat0_ where certifIcat0_.employee_id=? Certificate:MBACertificate:MCACertificate:PMP


Reference documents:

English: http://www.tutorialspoint.com/hibernate/hibernate_one_to_many_mapping.htm

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.