Hibernate Learning--set Collection configuration

Source: Internet
Author: User

Configuration of the Set collection

Data table creation: Table relationships an employee has multiple identities

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, employee_id INT DEFA Ult NULL, PRIMARY KEY (id));


Create the corresponding entity:

Package Com.study01;import Java.util.set;public class Employee {private int id;private string Firstname;private string LA stname;private int salary;private Set Certificates;public employee () {}public employee (string fname, string lname, int sal ary) {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 firstName) {this.firstname = FirstName;} Public String Getlastname () {return lastName;} public void Setlastname (String lastName) {this.lastname = LastName;} 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.study01;public class Certificate {private int id;private String name;public Certificate () {}public certificat E (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;//}if (This.name.equals (Obj2.getname ())) return True;return false;} public int hashcode () {int tmp = 0;TMP = (id + name). Hashcode (); return tmp;}}


Note that the Equals and Hashcode methods are overridden here. The elements in the set collection are not duplicated. Whether or not to repeat is compared by hashcode and the Equals method.

The Hibernate master configuration file is configured as follows:

<?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 test is the database name--><property name= " Hibernate.connection.url "> Jdbc:mysql://localhost/test </property><property name=" Hibernate.connection.username "> Root </property><property name=" Hibernate.connection.password "> 253503125 </property> <!--List of XML mapping files--><mapping resource= "Com/study01/employee.hbm.xml" /><mapping resource= "Com/study01/certificate.hbm.xml"/></session-factory></ Hibernate-configuration>


Configuration of the mapping file:

<?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 ">


<?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 ">


Test:

Package Com.study01;import Java.util.hashset;import java.util.iterator;import java.util.list;import java.util.Set; Import Org.hibernate.hibernateexception;import Org.hibernate.session;import Org.hibernate.sessionfactory;import Org.hibernate.transaction;import Org.hibernate.cfg.configuration;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 Exceptionininitializer Error (ex);} Manageemployee ME = new Manageemployee (); HashSet Set1 = new HashSet () Set1.add (New Certificate ("MCA")); Set1.add (New Certificate ("MBA")); Set1.add (new Certificate ("PMP")); Set1.add (New Certificate ("MCA"));/* Add employee records in the database */integer empID1 = me.addemp Loyee ("Manoj", "Kumar", 4000, Set1); HashSet Set2 = new HashSet () Set2.add (New Certificate ("BCA")); Set2.add (New Certificate ("BA")); Integer empID2 = Me.addemployee ("Dilip", "Kumar", +, Set2); Me.listemployees (); /* Update employee ' s salary Records */me.updateemployee (empID1, */me.deletee);/* Delete an employee from the database Mployee (empID2); /* List down all the Employees */system.out.println ("======================"); 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 = Facto Ry.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 ();}} }


Note The addition of two MCA in certificate. The results of the operation are as follows:

First Name:manoj last Name:kumar salary:4000certificate:pmpcertificate:mcacertificate:mbafirst Name:dilip last Name : Kumar salary:3000certificate:bcacertificate:ba======================first Name:manoj last Name:kumar salary:5000ce Rtificate:PMPCertificate:MCACertificate:MBA


The MCA only appeared once! Note the role of hashcode and equals in certificate.

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.