Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Hibernate example


May 17, 2021 Hibernate


Table of contents


Example

Let's look at an example of a stand-alone application that leverages Hibernate to provide Java persistence. W e'll create a Java application using Hibernate technology in different steps.

Create a POJO class

The first step in creating an application is to establish Java's POJO class or other classes, depending on the application that is about to be stored in the database. L et's consider using the getXXX and setXXX methods for our Employee classes to make them JavaBeans compliant classes.

POJO (Plain Old Java Object) is an object of Java that does not extend or execute special classes and whose interfaces are required by the EJB framework. A ll normal Java objects are POJO.

When you design a class that is stored in Hibernate, the most important thing is to provide JavaBeans-enabled code and properties in the Employee class that can be used as indexes like id properties.

public class Employee {
   private int id;
   private String firstName; 
   private String lastName;   
   private int salary;  

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

Create a database table

The second step is to create a table in your database. E ach object that you are willing to provide long-term retention will have a corresponding table. T he above objects need to be stored and retrieved in the following RDBMS tables:

create table EMPLOYEE (
   id INT NOT NULL auto_increment,
   first_name VARCHAR(20) default NULL,
   last_name  VARCHAR(20) default NULL,
   salary     INT  default NULL,
   PRIMARY KEY (id)
);

Create a mapping profile

This step is to create a mapping file to guide Hibernate on how to map the table of the database to define the class.

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

<hibernate-mapping>
   <class name="Employee" table="EMPLOYEE">
      <meta attribute="class-description">
         This class contains the employee detail. 
      </meta>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="firstName" column="first_name" type="string"/>
      <property name="lastName" column="last_name" type="string"/>
      <property name="salary" column="salary" type="int"/>
   </class>
</hibernate-mapping>

You'll need to save the mapped document in a file in .xml format of the <classname>.hbm.xml W e save the mapping document in Employee.hbm.xml file. L et's take a look at some of the small details related to the mapping document:

  • A mapped document is an XML-formatted document that has <hibernate-mapping> element, which contains all the elements of <class>
  • <class> specific map from the Java class to the database table. T he name of the Java class is specific, it uses the name property of the class element, and the name of the database table is specific, and it uses the table property.
  • <meta> can be used to create a description of the class.
  • <id> ID properties in the class to the database's main keyword table. T he name property of the id element relates to the properties in the class while the column property relates to the columns in the database table. type property has mastered the mapping type of hibernate, which will move from Java to SQL data type.
  • The element in the id <generator> automatically generate values for the primary keyword. S etting the class property of the generator element to native allows Hibernate to use identity, sequence, or hilo algorithms to create key keywords based on the performance of the underlying database.
  • <property> used to map the properties of a Java class to the database. T he name property of this element relates to the property in the class, and the column property relates to the columns in the data table. type property controls hibernate's mapping type, which goes from Java to SQL data type.

There are many other properties and elements in the mapping documentation that I'll cover in more detail as I explore other Hibernate-related topics.

Create an application class

Finally, we're going to use the main() method to create an application class to run the application. W e'll use this program to save some employee records, and then we'll apply CRUD operations to those records.

import java.util.List; 
import java.util.Date;
import java.util.Iterator; 

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();

      /* Add few employee records in database */
      Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);
      Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
      Integer empID3 = ME.addEmployee("John", "Paul", 10000);

      /* List down all the employees */
      ME.listEmployees();

      /* Update employee's records */
      ME.updateEmployee(empID1, 5000);

      /* Delete an employee from the database */
      ME.deleteEmployee(empID2);

      /* List down new list of the employees */
      ME.listEmployees();
   }
   /* Method to CREATE an employee in the database */
   public Integer addEmployee(String fname, String lname, int salary){
      Session session = factory.openSession();
      Transaction tx = null;
      Integer employeeID = null;
      try{
         tx = session.beginTransaction();
         Employee employee = new Employee(fname, lname, salary);
         employeeID = (Integer) session.save(employee); 
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
      return employeeID;
   }
   /* Method to  READ all the employees */
   public void listEmployees( ){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         List employees = session.createQuery("FROM Employee").list(); 
         for (Iterator iterator = 
                           employees.iterator(); iterator.hasNext();){
            Employee employee = (Employee) iterator.next(); 
            System.out.print("First Name: " + employee.getFirstName()); 
            System.out.print("  Last Name: " + employee.getLastName()); 
            System.out.println("  Salary: " + employee.getSalary()); 
         }
         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 ){
      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 an employee from the records */
   public void deleteEmployee(Integer EmployeeID){
      Session session = 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(); 
      }
   }
}

Compilation and execution

Here are the steps to compile and run the applications mentioned above. M ake sure you have PATH and CLASSPATH set up before compiling and executing the application.

  • Create the hibernate profile described in the settings .cfg.xml section.
  • Create the Employee.hbm map file .xml above.
  • Create the Employee file described .java source file and compile it.
  • Create the ManagementEmployee file described above .java source file and compile it.
  • Perform a binary ManageEmployee to run the program.

You will get the following results, and the records will be established in the EMPLOYEE table.

$java ManageEmployee
.......VARIOUS LOG MESSAGES WILL DISPLAY HERE........

First Name: Zara  Last Name: Ali  Salary: 1000
First Name: Daisy  Last Name: Das  Salary: 5000
First Name: John  Last Name: Paul  Salary: 10000
First Name: Zara  Last Name: Ali  Salary: 5000
First Name: John  Last Name: Paul  Salary: 10000

If you check your EMPLOYEE table, it will have the following records:

mysql> select * from EMPLOYEE;
+----+------------+-----------+--------+
| id | first_name | last_name | salary |
+----+------------+-----------+--------+
| 29 | Zara       | Ali       |   5000 |
| 31 | John       | Paul      |  10000 |
+----+------------+-----------+--------+
2 rows in set (0.00 sec

mysql>