Detailed Java Hibernate framework of the list map and bag mapping _java

Source: Internet
Author: User
Tags commit generator rollback sessions throwable unique id

List mapping table
A list is an element that a Java collection stores in a sequence and allows repeating elements. Users of this interface can accurately control the insertion of each element in the list. Users can access elements through their integer index and search for elements in the list. More formally, lists generally allow for elements E1 and E2, making E1.equals (E2), which typically allow multiple null elements if they allow null elements.

The list is mapped to the <list> element in the mapping table and initialized in Java.util.ArrayList.

To define an RDBMS table:
Consider a situation where the employee records are stored in the employee table and will have the following structure:

CREATE TABLE EMPLOYEE (
  ID INT not NULL auto_increment,
  first_name VARCHAR () default null,
  last_name varcha R () default NULL,
  salary   INT default null,
  PRIMARY KEY (ID)
);

Also, assume that each employee can have one or more certificates associated with him or her. The List collection mapping requires an indexed column in a collection table. The index column defines the location of the elements in the collection. Therefore, we will store the relevant information about the certificate in a separate table that has the following structure:

CREATE TABLE certificate (
  ID INT not NULL auto_increment,
  certificate_name VARCHAR () default NULL,
  IDX int default NULL, 
  employee_id int default NULL,
  PRIMARY KEY (ID)
);

There will be a relationship between multiple (One-to-many) employee and certificate objects.

Define the Pojo class:
Let's implement a Pojo class employee will be used to save objects in the Employee table and a collection of list variables with certificates.

Import java.util.*;
  public class Employee {private int id; 
  Private String FirstName;  
  Private String LastName;
  private int salary;

  private List 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;
  The 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;
  The public void setsalary (int salary) {this.salary = salary;
  Public List getcertificates () {return certificates;
  The public void Setcertificates (List certificates) {this.certificates = certificates;

 }
}

We need the corresponding certificate table to define another Pojo class, so that the certificate object can store and retrieve the certificate table.

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

To define a hibernate mapping file:
Let's develop a mapping file that specifies how classes defined by Hibernate map to database tables. The <list> element will be used to define rules that use the list collection. The index of the table is an integer type and always uses the <list-index> element definition mapping.

<?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 format <classname>.hbm.xml in the mapping file that should be saved. We save the file Employee.hbm.xml in our mapping file. You are already familiar with most of the mapping details, mapping all the elements in the file:

A mapping document is an XML document that has

<class> elements are used to define database tables from a Java class-specific mapping. The Java class name specifies that the name property of the class element is used and the Table property database table name is used.

The <meta> element is an optional element that you can use to create a description of the class.

The <id> element maps the unique ID attribute in the class to the primary key of the database table. The Name property of the ID element refers to the columns of the property's class and column property that are in the database table. The Type property holds the Hibernate mapping type, which is converted from Java to SQL data type.

The primary key value that the <generator> element within the ID element is used to automatically generate. Setting the class attribute of the build element to native lets hibernate pick up algorithms in either identity,sequence or Hilo to create a primary key based on the support capabilities of the underlying database.

The <property> element is used to map the properties of a Java class to columns in a database table. The Name property of an element refers to the columns of the property's class and column property that are in the database table. The Type property holds the Hibernate mapping type, which is converted from Java to SQL data type.

The <list> element is used to set the relationship between the certificate and the Employee class. We use the <list> element in the Cascade property to tell Hibernate to save the object of the certificate, and also to the employee object. The Name property is set to the listvariable defined in the parent class, and in our case it is a certificate.

The <key> element is the parent object that contains the foreign key, which is the column in the certificate table. That is, table employee.

The <list-index> element defines the position of the component to hold and is mapped to the indexed column in the collection table. The index of the persistence list starts at zero. You can change this, for example, in your mapping <list-index base= "1" .../>.

The <one-to-many> element represents an employee object that involves many certificates, and therefore the certificate object must be related to the worker's parent. You can use any and <one-to-one>,<many-to-one> to do or <many-to-many> this element according to your needs. If we change this example using a many-to-many relationship, we need a mapping between the associated table and the parent and child objects.

To create an application class:
Finally, we will create the main () method of the application class to run the application. We will use this application to save some of the employee's records along with the certificate, and then we will apply the crud operation on the record.

Import java.util.*; 
Import org.hibernate.HibernateException; 
Import org.hibernate.Session;
Import org.hibernate.Transaction;
Import Org.hibernate.SessionFactory;

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 Exceptionininitializererror (ex);
   Manageemployee ME = new Manageemployee ();
   /* Let us have a set of certificates for the "the" "the"/ArrayList Set1 = new ArrayList ();
   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 * * ARRAYlist Set2 = new ArrayList ();
   Set2.add (New certificate ("BCA"));

   Set2.add (New certificate ("BA"));

   /* ADD Another employee record in the database */Integer empID2 = Me.addemployee ("Dilip", "Kumar", 3000, Set2);

   /* List down all the employees * * Me.listemployees ();

   /* Update employee ' s salary records * * Me.updateemployee (empID1, 5000);

   /* 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, ArrayList 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 employees detail/public void Listemployees () {Sessions session = Factory.opensessio
   N ();
   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 ("Name:" + employee.getfirstname ()); 
      System.out.print ("Last Name:" + employee.getlastname ());
      System.out.println ("Salary:" + employee.getsalary ());
      List certificates = employee.getcertificates (); for (Iterator Iterator2 = Certificates.iterator (); Iterator2.hasnext ();) {certificate CertName = (C 
         ertificate) 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 for an employee */public void UpdateEmployee (Integer EmployeeID, int salary) {Se
   Ssion 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 S
   Ession = Factory.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 ();

 }
  }
}

Compiling and executing:
Here is a step to compile and run the above application. Make sure that you have set up path and classpath appropriately before compiling and executing.

    • Create a configuration section explanation in the Hibernate.cfg.xml configuration file.
    • Create the Employee.hbm.xml mapping file, as shown in the previous illustration.
    • Create the Employee.java source file, as shown in the figure above, and compile it.
    • Create the Certificate.java source file, as shown in the figure above, and compile it.
    • Create the Manageemployee.java source file, as shown in the figure above, and compile it.
    • Executes the Manageemployee binary file to run the program.

The following results are obtained on the screen, and records are created on both the employee and the certificate table. You can see that the certificate has the opposite sort order. You can try by changing the mapping file by simply setting the sort= "natural" and executing the program and comparing the results.

$java Manageemployee
....... Various LOG MESSAGES would DISPLAY

here ... Name:manoj last Name:kumar salary:4000
certificate:mca
certificate:mba
certificate:pmp
Name:dilip last Name:kumar salary:3000
certificate:bca
certificate:ba the last Name:manoj
R salary:5000
certificate:mca
Certificate:mba
CERTIFICATE:PMP

If you check the Employee and certificate table, you should record:

Mysql> select * from EMPLOYEE;
+----+------------+-----------+--------+
| id | first_name | last_name | salary
| +----+------------+-----------+--------+
| 51 | Manoj   | Kumar   |  5000 |
+----+------------+-----------+--------+
1 row in Set (0.00 sec)

Mysql> select * from certificate;
+----+------------------+------+-------------+
| id | certificate_name | idx | employee_id
| +----+------------------+------+-------------+
| 6 | MCA       |  0 |     Wuyi |
| 7 | MBA       |  1 |     Wuyi |
| 8 | PMP       |  2 |     Wuyi |
+----+------------------+------+-------------+
3 rows in Set (0.00 sec)

Alternatively, you can map a Java array instead of a list. An array of mappings is almost identical to the preceding example, except with the different element and attribute names (<array> and <array-index>). However, as explained earlier, Hibernate applications rarely use arrays.

Bag mapping
Bag is a Java collection storage element that does not need to care about the order, but allows repeating elements in the list. Bag is a random grouping of objects in the list.

The collection collection is mapped to <bag> components in the mapping table and initialized with Java.util.ArrayList.
The RDBMS table and the Pojo class in the following example still use the above definition.
To define a hibernate mapping file:
Let's develop a mapping file that instructs hibernate how to define a class to map to a database table. The <bag> element will be used to define the collection rules used.

<?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 format <classname>.hbm.xml in the mapping file that should be saved. We save the mapping file Employee.hbm.xml. We are already familiar with most of the mapping details, but let's see all the elements in the mapping file again:

A mapping document is an XML document that has

<class> elements are used to define database tables from a Java class-specific mapping. The Java class name specifies that the name property of the class element is used and the Table property database table name is used.

The <meta> element is an optional element that you can use to create a description of the class.

The <id> element maps the unique ID attribute in the class to the primary key of the database table. The Name property of the ID element refers to the columns of the property's class and column property that are in the database table. The Type property holds the Hibernate mapping type, which is converted from Java to SQL data type.

The primary key value that the <generator> element within the ID element is used to automatically generate. Setting the class attribute of the build element to native lets hibernate pick up algorithms in either identity,sequence or Hilo to create a primary key based on the support capabilities of the underlying database.

The <property> element is used to map the properties of a Java class to columns in a database table. The Name property of an element refers to the columns of the property's class and column property that are in the database table. The Type property holds the Hibernate mapping type, which is converted from Java to SQL data type.

The <bag> element is used to set the relationship between the certificate and the Employee class. We use the <bag> high element of the Cascade property to tell Hibernate to save the object of the certificate, as well as the employee object. The Name property is set to the Definedcollection variable in the parent class, which in our case is the certificate.

The <key> element is the parent object that contains the foreign key, which is the column in the certificate table. Table employee.

The <one-to-many> element indicates that an employee object involves many certificates, and therefore a certificate object must have an association with the employee parent class. You can use the <one-to-one>,<many-to-one> or <many-to-many> element as needed.

To create an application class:
Finally, we will create the main () method of the application class to run the application. We will use this application to save some of the employee's records along with the certificate, and then we will apply the crud operation on the record.

Import java.util.*; 
Import org.hibernate.HibernateException; 
Import org.hibernate.Session;
Import org.hibernate.Transaction;
Import Org.hibernate.SessionFactory;

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 Exceptionininitializererror (ex);
   Manageemployee ME = new Manageemployee ();
   /* Let us have a set of certificates for the "the" "the"/ArrayList Set1 = new ArrayList ();
   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 * * ARRAYlist Set2 = new ArrayList ();
   Set2.add (New certificate ("BCA"));

   Set2.add (New certificate ("BA"));

   /* ADD Another employee record in the database */Integer empID2 = Me.addemployee ("Dilip", "Kumar", 3000, Set2);

   /* List down all the employees * * Me.listemployees ();

   /* Update employee ' s salary records * * Me.updateemployee (empID1, 5000);

   /* 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, ArrayList 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 employees detail/public void Listemployees () {Sessions session = Factory.opensessio
   N ();
   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 ("Name:" + employee.getfirstname ()); 
      System.out.print ("Last Name:" + employee.getlastname ());
      System.out.println ("Salary:" + employee.getsalary ());
      Collection certificates = employee.getcertificates (); for (Iterator Iterator2 = Certificates.iterator (); Iterator2.hasnext ();) {certificate CertName = (C 
         ertificate) 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 for an employee */public void UpdateEmployee (Integer EmployeeID, int salary) {Se
   Ssion 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 S
   Ession = Factory.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 ();

 }
  }
}

Compiling and executing:

The following results are obtained on the screen, and records are created on both the employee and the certificate table. You can see that the certificate has the opposite sort order. You can try by changing the mapping file by simply setting the sort= "natural" and executing the program and comparing the results.

$java Manageemployee
....... Various LOG MESSAGES would DISPLAY

here ... Name:manoj last Name:kumar salary:4000
certificate:mca
certificate:mba
certificate:pmp
Name:dilip last Name:kumar salary:3000
certificate:bca
certificate:ba the last Name:manoj
salary:5000
certificate:mca
Certificate:mba
CERTIFICATE:PMP

If you check the Employee and certificate table, you should record:

Mysql> select * from EMPLOYEE;
+----+------------+-----------+--------+
| id | first_name | last_name | salary
| +----+------------+-----------+--------+
| 53 | Manoj   | Kumar   |  5000 |
+----+------------+-----------+--------+
1 row in Set (0.00 sec)

Mysql> select * from certificate;

+----+------------------+-------------+
| id | certificate_name | employee_id
| +----+------------------+-------------+
| 11 | MCA       |     |
| 12 | MBA       |     |
| 13 | PMP       |     |
+----+------------------+-------------+
3 rows in Set (0.00 sec)
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.