First Hibernate Application

Steps to prepare First Hibernate Application
  1. Prepare Persistence Class or Object
  2. Prepare Mapping File
  3. Prepare Hibernate Configuration File
  4. Prepare Hibernate Client Application

Note

To run Hibernate Applications we have to download all Hibernate JAR file and we have to them for our Hibernate application.

1. Prepare Persistence Class or Object

The main intention of Persistence class or object in Hibernate applications is to manage Persistence data which we want to store in Database or by using this we want to perform the database operations like select, update, delete

In Hibernate applications, to prepare Persistence classes we have to use the following Guidelines

  • In Hibernate applications Persistence classes must be POJO classes [Plain Old Java Object], they must not extend or implement predefined Library.
  • In hibernate Applications Persistence classes must be public, Non abstract and non-final.
    • Where the main intention to declare persistence classes as public is to bring persistence classes scope to Hibernate software in order to create objects.
    • Where the main intention to declare persistence classes as Non abstract is to allow to create Objects for Persistence classes.
    • Where the main intention to declare persistence classes as Non final is to allow to extend one persistence class to another persistence class as per the requirement.
  • In Persistence classes all Properties must be declared as per database table provided columns, where names are not required to be matched, but, data types must be compatible.
  • In Persistence classes, all properties must be declared as private in order to improve Encapsulation.
  • In Persistence classes , we must define a separate set of setXXX () and getXXX () methods for each and every property
  • In persistence classes, we must declare all methods are public.
  • In Persistence classes, if we want to provide any constructor then it must be public and 0- arg constructor, because, while creating object for persistence class Hibernate software will search and execute only public and 0-arg constructor.
  • In Hibernate applications , if we want to provide our own comparison mechanisms while comparing Persistence objects then it is suggestible to Override equals(–) method.
  • In Hibernate applications, if we want to provide our own hash code values then it is suggestible to Overrid hashCode () method.
  • In Hibernate applications, we will use POJO classes, which are not extending and implementing predefined library, but, it is suggestible to implement java.io.Serializable marker interface in order to make eligible Persistence object for Serialization and Deserialization.
  • In Persistence classes, we have to declare a property as an ID property, it must represent primary key column in the respective table.

Example

package com.ashok.hibernate.sample.model;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class Employee {
	private int id;
	private String empName;
	private String address;
	private double salary;
	
	public Employee(String empName, String address, double salary) {
		super();
		this.empName = empName;
		this.address = address;
		this.salary = salary;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getEmpName() {
		return empName;
	}

	public void setEmpName(String empName) {
		this.empName = empName;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public double getSalary() {
		return salary;
	}

	public void setSalary(double salary) {
		this.salary = salary;
	}
}
2. Prepare Mapping File

The main intention of mapping file in Hibernate applications is to provide mapping between a class, id property and normal properties from Object Oriented Data Model and a table, primary key column and normal columns from Relational data model.

In Hibernate applications, mapping file is able to provide the mapping details like Basic OR mapping, Component mapping, inheritance mapping, Collections mapping, Associations mapping.

To prepare mapping file in Hibernate applications we have to provide mapping file name with the following format.

POJO_Class_Name.hbm.xml

The above format is not mandatory, we can use any name but we must provide that intimation to the hibernate software.

In Hibernate applications, we can provide any no of POJO classes, w.r.t each and every POJO class we can define a separate mapping file.

Note

  • In Hibernate applications, it is possible to configure more than POJO class in single mapping file.
  • Up to Hibernate3.2.5 version Hibernate Mapping file is mandatory to provide mapping details, but, right from Hibernate3.2.5 version mapping file is optional, because, Hibernate 3.2.5 version has provided annotations as an alternative to mapping file.

To provide Basic mapping between POJO class and table in mapping file we have to use the following XML tags provided by Hibernate.

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

<hibernate-mapping>
	<class name="com.ashok.hibernate.sample.model.Employee" table="emp">
		<meta attribute="class-description">
			This class contains the employee detail.
		</meta>
		<id name="id" type="int" column="id">
			<generator class="native" />
		</id>
		<property name="empName" column="emp_name" type="string" />
		<property name="address" column="address" type="string" />
		<property name="salary" column="salary" type="double" />
	</class>
</hibernate-mapping>
  • Where <hibernate-mapping> tag is root tag in mapping file, it will include no of classes configuration.
  • Where <class> tag is able to provide single POJO class configuration in order to provide mapping between POJO class name and the respective table name.
  • Where “name” attribute in <class> tag is able to provide fully qualified name of the POJO class.
  • Where “table” attribute in <class> tag is able to provide the respective table name.
  • Where <id> tag is able to provide ID property configuration in order to provide mapping between ID property and the respective primary key column.
  • Where “name” attribute in <id> tag is able to provide id property name of the POJO class.
  • Where “column” attribute in <id> tag is able to provide primiry key column defined in table.
  • Where <property> tag is able to provide normal bean property configuration in order to provide mapping between normal bean property and normal table column.
  • Where “name” attribute and “column” attribute will take bean property name and table column name respectively.

Note

If bean property names and table column names are same then it is optional to provide “column” attribute in mapping file.

3. Prepare Hibernate Configuration File

The main purpose of hibernate configuration file is to provide all configuration details of hibernate application which includes JDBC parameters to prepare connection, Transactions configurations, Cache mechanisms configurations, Connection pooling configurations etc.

In Hibernate applications, the standard name of hibernate configuration file is “hibernate.cfg.xml”, it is not fixed, we can provide any name but that name must be given to Hibernate software.

In Hibernate applications, we are able to provide more than one configuration file, but, for each and every database, that is, in hibernate applications if we use multiple databases then we are able to prepare multiple configuration files.

To prepare hibernate configuration file with basic configuration details we have to use the following XML tags.

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.OracleDialect</property>
      <property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
      <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
      <property name="hibernate.connection.username">system</property>
      <property name="hibernate.connection.password">ashok</property>

      <property name="hbm2ddl.auto">update</property>

      <mapping resource="com/ashok/hibernate/sample/employee.hbm.xml"/>
   </session-factory>
</hibernate-configuration>
  • Where <hibernate-configuration? is root tag.
  • Where <session-factory> tag is able to include hibernate properties configurations.
  • Where <property> tag is able to provide single property configuration.
  • Where “name” attribute in <property> tag is able to provide property name and body of the <property> tag will take property value.
  • Where <mapping> tag is able to provide mapping file configuration.
  • Where “resource” attribute is able to provide mapping file name and location.
About Dialect in Hibernate 
  • Dialect class is a simple java class, which contains mapping between java language data type and database data type.
  • Dialect class contains queries format for predefined hibernate methods.
  • Hibernate generates queries for the specific database based on the Dialect class. If you want to shift from one database to another just change the Dialect class name in hibernate.cfg.xml file.
  • All Dialect classes must extend ‘Dialect’ (abstract) class
  • Hibernate supports almost 30 dialect classes.
  • If we want we can write our own dialect by extending Dialect class
  • Dialect class is used convert HQL queries into database specific queries.

E.g

org.hibernate.dialect.Oracle9Dialect
org.hibernate.dialect.Oracle10gDialect
org.hibernate.dialect.MySQLDialect

4. Prepare Client Application

The main intention of Hibernate Client application is to activate Hibernate Software, creating persistence objects and performing Persistence operations.

To prepare Client Application in hibernate applications we have to use the following steps as per Hiberante3.x version.

  1. Create Configuration class object
  2. Create Session Factory object
  3. Create Session Object
  4. Create Transaction object if it is required.
  5. Perform Persistence operations
  6. Close Session Factory and Session objects.
1. Create Configuration class object

In Hibernate, the main intention of Configuration object is to store all the configuration details which we provided in hibernate configuration file.

To represent Configuration object Hibernate has provided a predefined class in the form of “org.hiberante.cfg.Configuration”.

To create Configuration class object we have to use the following constructor from Configuration class.

public Configuration()

E.g

Configuration cfg = new Configuration();

If we use the above instruction in Hibernate applications then we are able to get an empty.

Configuration object in heap memory, it will not include any Configuration details.

If we want to store Configuration details from Configuration file we have to use either of the following methods.

1. public Configuration configure()

This method will get configuration details from the configuration file with the name hibernate.cfg.xml

2. public Configuration configure(String configFileName)

This method can be used to get configuration details from hibernate configuration file with any name, it will be used when we change configuration file name from hibernate.cfg.xml file to some other name .

3. public Configuration configure(File file)

This method can be used to get configuration details from a file which is represented in the form of java.io.File class object.

public Configuration configure(URL url)

This method can be used to get Configuration details from a file which is available in network represented in the form of java.net.URL .

E.g

Configuration cfg = new Configuration();
cfg.configure();

When we use configure() method then Hibernate Software will search for hibernate.cfg.xml file, if it is available then Hibernate software will load the content of hibernate.cfg.xml file, parse it and read content from configuration file to Configuration object.

2. Create Session Factory object

In Hibernate, the main intention of Session Factory object is to manage Connections, Statements, Cache levels, etc and it able to provide no of Hibernate Session objects.

To represent Session Factory object Hibernate has provided a predefined interface in the form of “org.hibernate.Session Factory”.

To get Session Factory object we have to use the following method from Configuration class.

public Session Factory buildSessionFactory()

E.g

SessionFactory sf = cfg.buildSessionFactory();

Note

The above approach to get Session Factory object is available up to Hibernate 3.x version, buildSessionFactory() was deprecated in Hibernate 4.x version.

In Hibernate applications, if we use multiple Databases then we have to prepare multiple Configuration files, multiple Configuration Object, w.r.t this, we have to prepare multiple Session Factory objects.

Session Factory object is heavy weight and it is thread safe up to a particular Database, because, it able to allow more than one thread at a time.

3. Create Session Object

In Hibernate, for each and every database interaction a separate Session will be created. In Hibernate, Session is able to provide no of persistence methods in order to perform persistence operations.

To represent Session object, Hibernate has provided a predefined interface in the form of “org.hibernate.Session”. To get Session object, we have to use the following method from Session Factory.

public Session openSession();

E.g

Session s =sf.openSession();

In Hibernate, Session object is light weight and it is not thread safe, because, for each and every thread a separate Session object will be created.

4. Create Transaction Object

Transaction is a unit of work performed by Front End applications on Back end systems. To represent Transactions, Hibernate has provided a predefined interface in the form of “org.hibernate.Transaction”.

To get Transaction object we will use either of the following methods.

1. public Transaction getTransaction()

It will return Transaction object with out begin, where to begin Transaction we have to use the following method.

public void begin()

2. public Transaction beginTransaction()

It will return Transaction and begin Transaction. In Hibernate applications, after performing persistence operations we must perform either commit or rollback operations in order to complete Transactions, for this, we have to use the following methods from Transaction.

public void commit()
public void rollback()

Note

In Hibernate applications, Transaction is required for only Non Select operations, not required for Select operations.

5. Perform Persistence Operations

In Hibernate applications, to perform persistence operations Session has provided the following methods.

To insert an object or record into Database table we have to use the following methods.

save(Object obj)
persist(Object obj)

To update a record ion database table we have to use the following methods.

update(Object obj)
saveOrUpdate(Object obj)

To delete a record from database table we have to use the following method.

public void delete(Object obj) throws HibernateException

To retrieve a record from database table we have to use the following methods.

get()
load()
6. Close Session and SessionFactory

In Hibernate applications, it is convention to close Session and Sessionfactory objects at the end of client application in order to avoid security problems.

public void close()throws HibernateException.

E.g

s.close();
sf.close();
First Hibernate Application
Scroll to top