Nearby lessons

1 of 19

Hibernate - Introduction

📌 What You Will Learn
  • Understand Hibernate - Introduction
  • See working code examples
  • Learn from common mistakes and Q&A

Learn Hibernate - Introduction step by step — simple explanations, complete programs with their output, common beginner mistakes, and exam-style MCQs.

Data Persistency

Representing Data permanently in Backend systems is called as "Data Persistency".

To achieve Data Persistency in database applications we will use a set of Operations [CRUD]

called as Date Persistence Operations".

To achieve Data Persistency in Enterprise Applications we will use a set of tech called as "Data

Persistency Tech".

To achieve Data Persistency in enterprise applications we will use the following technologies w.r.t

JAVA.

Data Persistency

b) EJBs Entity Beans

c) JPA

d) Open JPA

e) Toplink

Data Persistency through Serialization and Deserialization: The process of

Separating Data from an Object is called as "Serialization".

The process of regenerating an object on the basis of Data is called as "Deserialization".

To perform Serialization and Deserialization JAVA has provided the following two byte oriented

streams

  • Object OutputStream for Serialization
  • Object InputStream for Deserialization

Steps to perform Serialization:

  • Prepare Serializable class by implementing java.io.Serializable marker interfae:

class Employee implements Serializable{

-------

}

Employee emp1 = new Employee();

  • Create FileOutputStream object:

FileOutputStream fos = new FileOutputStream("emp.txt");

  • Create ObjectOutputStream for Serialization.

ObjectOutputStream oos = new ObjectOutputStream(fos);

  • Write Serializable Object in ObjectOutputStream:

oos.writeObject(emp1);

Steps to perform Deserialization:

  • Create FileInputStream from Source File:

FileInputStream fis = new FileInputStream("emp.txt");

2.Create ObjectInputStream for Deserialization:

ObjectInputStream ois = new ObjectinputStream(fis);

3.Read Deserialized Object from ObjectInputStream:

Employee emp2 = (Employee)ois.readObject();

In Serialization and Deserialization Data Persistency mechanism, we will store data in file

system ,where file system is providing permanent storage for our data, so that, Serialization

and Deserialization is a Data Persistency Mechanism.

In Serialization and Deserialization data persistency mechanism, we will use a flat file to

store data, it is platform dependent, it is not suitable for the platform independent front end

technologies like JAVA, .NET,....

In Serialization and Deserialization Data Persistency mechanism, we will use two byte

oriented streams like ObjectOutputStream and ObjectInputStream to perform Serialization

and Deserialization, so that, this data persistency mechanism is suitable for only byte

oriented data.

In this data persistency mechanism, we are using file system to store data , it able to store

less data , it able to provide less security and it able to increase data redundancy, it is not

suggestible in applications.

This persistency mechanism is suitable for Standalone applications, not suitable for

enterprise applications.

If we use this data persistency mechanism in Enterprise applications then we have to

provide lot of java code.

In Serialization and Deserialization data persistency mechanism we are able to perform

only insertion and retrieval operations, we are unable to perform update, delete,...

operations.

In this data persistency mechanism, query language support is not existed so that database

operations are very much difficult.

Example02
JCode Cell
1 
2Serialization and Deserialization
3JDBC
4ORM Implementationsa) Hibernate
5

Data Persistency through JDBC

JDBC is a step by step process or a technology or an API or the collection of predefined classes

and interfaces or an abstraction, it will provide very good environment to interact with database

from java applications in order to perform database operations from java applications.

To prepare JDBC applications we have to use the following steps.

  • Load and Register Driver:

Class.forName("oracle.jdbc.OracleDriver");

  • Enstablish Connection between Java application and Database.

Connection con = DriverManager.getConnection(" jdbc:oracle:thin:@localhost:1521:xe",

"system", "durga");

  • Create either Statement or PreparedStatement or CallableStatement as per the

requirement.

Statement st = con.createStatement();

  • Write and execute SQL Queries.

ResultSet rs = st.executeQuery("select * from emp1");

  • Close the resources.

rs.close();

st.close();

con.close();

In Jdbc Applications, when we establish Connection between java application and

database , automatically, the generated Connection will be available in "Auto-Commit"

mode, in this mode, if we submit an sql query to the Connection then Connection will carry

that sql query to Database Engine and Connection will make Database Engine to execute

SQL Query and to results in Database Permanently, this Nature of Connection is able to

achieve Data Persistency in JDBC Applications.

In JDBC applications, we have provide SQL Queries explicitly to perform database

operations, So that, Developers must required SQL Awareness.

In JDBC applications, developers must have explicitly concentration on Driver

Management, Connection Management and Statement Management.

In JDBC Applications, the steps like Load and Register Driver, Establish Connection ,

Create Statement and Close resources ... are common ion every JDBC Application, we

must write repeatedly, it will increase Code duplication .

In Jdbc applications, we have to hardcode the JDBC Parameters like Driver class name,

Driver URL, Database User Name and Databse password,...

In JDBC , Transactions support is not good.

In JDBC almost all the exceptions are checked exceptions, we must handle them by

providing JAVA code.

In JDBC applications, if we retrive data from database then that will be stored in ResultSet

object at java applications, it is not implementing java.io.Serializable interface and which is

not eligible to carry in network.

Data Persistency through ORM

In general, in Enterprise Applications to represent data we will use more than one data model like

Object Oriented Data Model, Relational data Model,.....

  • Paradigm Mismatches:

In enterprise applications both the data models are having their own approaches to represent data

in effective manner, these differences are able to provide Paradigm Mismatches, and these

mismatches are able to reduce data persistency in enterprise applications.

In general, Object Oriented Data Model and Relational data model are having the following

mismatches.

In general, Object Oriented Data Model and Relational data model are having the following

mismatches.

In general, Object Oriented Data Model and Relational data model are having the following

mismatches.

In general, Object Oriented Data Model and Relational data model are having the following

mismatches.

  • Granularity Mismatch
  • Sub types mismatch
  • Associations Mismatch
  • Identity Mismatch

To improve Data persistency in Enterprise applications we have to resolve the above specified

mismatches between Data models, for this, we have to use "ORM" implementations.

  • Granularity Mismatch:

In general, Granualarity is representing a count .

EX: In a database no of tables , in a table no of columns, In a class no of properties, in an

application no of classes,.....

IN Enterprise applications, we are able to represent an User in Object Oriented Data Model

in one approach and in Relational data Model in another approach.

In Object oriented Data model we may take a class User with the properties uname, uage

,... to represent an User , here if we want to represent address details of an user then we

will take a seperate class Address with the properties like pno, street, city,.... and we will

declare Address class reference variable in User class.

In Relational data Model, we may represent a User entity and its address details in the form

of a single table or in the form of multiple tables with primary key and foreign key

relationship.

In the above context, the no of classes [Granularity] in Object Oriented Data Model and the no of

tables [Granularity] in Relational data model may not be matched, it may reduce data persistency

in enterprise applications, in this context, to improve Data persistency we have to use ORM

implementations like Hibernate.

For the above Granularity mismatch, Hibernate has provided a solution in the form of

"Component Mapping".

  • Sub types Mismatch:

In Object Oriented Data Model we are able to use inheritance inorder to improve Code

Reusability. In Java applications, we are able to represent inheritance by using "extends"

keyword.

In Relational data Model, we are not having any feature to represent inheritance between

tables, in Relational Data model we are able to achieve inheritance kind of feature by using

either of the following approaches.

  • We may take single table to represent all the properties of the classes which are included

in inheritance.

  • We may take a seperate table for each and every sub class with the super class

properties and sub class properties.

  • We may take a seperate table for super class and for sub classes with Primary Key and

Foreign Key relationships.

In the aboce context, Object Oriented Data Model is having its own representation to

achieve INheritance and relational Data Model is having its own approaches to represent

Inheritance kind of feature, this difference is representing "Inheritance Mismatch", It may

reduce data persistency in enterprise applications.

In the above context, to improve Data Persistency we have to resolve Inheritance Mismatch

problem, for this, we have to use ORM implementations like Hibernate.

For the above Inheritance Mismatch, Hibernate has provided the following three types of

solutions.

  • Table Per Class Hierarchy.
  • Table Per Sub class
  • Table Per Concrete Class
  • Associations Mismatch:

IN general, in enterprise applications we will use Associations to improve communication

between entities and to improve data navigation between entities.

In Object Oriented data Model, we are able to implement associations by declaring either

single reference variable or array or collection of reference variables of a class in another

class.

In Relational Data Model , we are able to achieve associationes between entities either by

defining Primary-Key and Foreign-Key relationships between entity tables or by using join

columns or by using join tables between entity tables.

In the above context, Object Oriented Data Model and Relational data Model both are

having their own apporoaches to implement Associations, this difference in their

approaches may create mismatch between these two data models, it may reduce Data

Persistency in enterprise applications.

In the above context, to improve data persistancy we have to resolve associattions

mismatch between data models, for this, we have to use ORM. Hibernate is one of the

ORM implementation, it will provide solution for association mismatch in the form of

"Associations Mapping" as part of Hibernate Mapping feature.

  • Identity mismatch:

In Object Oriented model, we are able to represent all the entities in the form of classes.

In Object Oriented model, we are able to prepare no.of instances from a particular class.

In the above context, it is possible to check whether the two objects are identical or not by

using either == operator or .equals ( ) method from object class.

In case of relational model, all the records in the entity tables be identical if we use

primary key column.so that no specific mechanism is existed to check whether the two

records are identical or not.

If we consider the above two data models. There is a mismatch about identity checking, it

will make data persistency is compel.

In the above context, to simplify data we have to use ORM implementations. With respect

to java technology.

ORM is a set of rules and regulations or a set guidelines to provide mapping between

Object Oriented Programming elements like classes, id properties, normal properties and

the relational data model elements like table, primary key columns, and normal columns

either by using XML file or by using Annotations.

Examples:

  • EJB'S
  • HIBERNATE
  • JPA
  • TOPLINK
  • OPEN JPE
  • EJB Vs HIBERNATE:

WHAT IS THE DIFFERENCE B/W EJB&HIBERNATE?

i. In case of EJB'S entity beans, we should require 1-1 relation b/w database table and the

entity classes. But it is not mandatory in case of hibernate.in case of hibernate, a single

entity class may represent multiple no.of tables and single table may represent multiple

no.of entity classes.

ii. EJB'S entity beans is more API dependent because in EJB'S entity beans all the entity

classes must implement or extend predefined library provided by EJB API.

iii. hibernate is less API dependent because in Hibernate all the entity classes are by default

POJO classes(plain old java object),these are normal java bean classes which should not

extend (or) implement any predefined library.

iv. Due to the above reasons, Testing & Debugging is very difficult in entity but which are

very simple incase of Hibernate.

v. In case of entity beans, all the bean classes are not participated in inheritance directly.

But in case of hibernate, it is possible to provide inheritance relation b/w POJO classes.

vi. EJB'S entity beans should require application server to execute. But hibernate

applications will be executed with or without application server.

vii. Due to the above reasons, entity beans portability is very less. Due to the above reason,

hibernate portability is very good.

viii. Due to the above reason entity bean is heavy weight data persistency solution. Due to

the above reason, hibernate is light weight data persistency solution.

ix. Entity beans are relatively slow and hibernate is faster data persistency solution except

startup.

  • JPA Vs HIBERNATE:

What is the difference between JPA and Hibernate?

JPA is an abstraction provided by SUN Microsystems and implemented by all Application

Server vendors like Web logic Server vendor, JBOSS Server vendor,..... JPA provides a set

of conventions to implement ORM rules and regulations.

Hibernate is a product, it has implemented ORM rules and regulations as per JPA

guidelines in order to provide data Persistency in enterprise applications.

Hibernate History

Home: Read Hat
Objective: To simplify data persistency in Enterprise
Author: Gavin King
Type: ORM Implementation Product.
Open/Licenced: Open Source Software.
Initial Version: Hibernate1.0 [2001]
User versions: Hibernate3.x [2005]
Latest VersionHibernate4.x [2011]
Designed On: Hibernate5.x [2017]

Website : JAVA

: www.hibernate.org

Hibernate Features

  • Hibernate is Database independent, it can be used for any type of Database.
  • Hibernate is applicable for both standalone applications and Enterprise Applications.
  • Hibernate is providing very good support for Associations and Joins.
  • Hibernate is having very good Annotations in order to reduce XML tech dependency in

enterprise applications.

  • Hibernate is having very good implementations for Primary key generation algorithms in

order to generate and insert a unique primary key value for each and every insertion

operation.

  • Hibernate is providing very good Collections support to manage data.
  • Hibernate is having its own query language, which is database independent, Object

Oriented, that is, HQL in order to perform database operations.

  • Hibernate has provided very good Cache mechanisms in order to reuse the results.
  • Hibernate is having very good support for Connection Pooling mechanisms in order to

improve Connection re usability.

  • Hibernate is supported by almost all IDEs and Application Servers.
  • Hibernate is against for SQL Queries in enterprise applications directly, but, if we want

to write database dependent sql queries then it is possible to provide database

dependent sql queries by using "Native SQL".

  • Hibernate has provided very good transactions support.

Hibernate Architecture

From the above Arch.,

Hibernate Configuration File will provide all the configuration details like driver class name, driver

URL, Database User name , Database password,.... which we required to establish connection

with database and to setup JDBC environment.

Hibernate Mapping file will provide all the mapping details like Bean Class name and Database

table name, ID property and Primary key column , Normal Properties and Normal Columns,....

Hibernate Architecture

details from hibernate configuration file and Hibernate Software will set up the required

JDBC Environment to perform database operations.

Example08
JCode Cell
1 
2Client Application will perform the following three actions in Hibernate applications mainly.
3Activating Hibernate Software, in this case, Hibernate Software will take all configuration
4

Hibernate Architecture

When Client Application perform persistence operation, Hibernate Software will perform the

following actions.

Example09
JCode Cell
1 
2Prepare Persistence Object with the persistence data.
3Perform Persistence Operation.
4

Hibernate Architecture

table name and all column names on the basis of Persistence object.

Example10
JCode Cell
1 
2Hibernate Software will take persistence method call and identify persistence Object.
3Hibernate Software will take all mapping details from hibernate mapping file like database
4

Hibernate Architecture

names and column names and with the persistence object provided data.

Example11
JCode Cell
1 
2Hibernate Software will prepare database dependent sql query on the basis of table
3

Hibernate Architecture

the required persistence operation.

Steps to prepare First Hibernate Application

Steps to prepare First Hibernate Application:

Example12
JCode Cell
1 
2Hibernate Software will execute the generated database dependent sql query and perform
3

Hibernate Architecture

Note: To run Hibernate Applications we have to download all Hibernate JAR file and we have to

them for our Hibernate application.

Example13
JCode Cell
1 
2Prepare Persistence Class or Object.
3Prepare Mapping File.
4Prepare Hibernate Configuration File
5Prepare Hibernate Client Application
6

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

1) Prepare Persistence Class or Object

Object], they must not extend or implement predefined Library.

Example15
JCode Cell
1 
2In Hibernate applications Persistence classes must be POJO classes [Plain Old Java
3

1) Prepare Persistence Class or Object

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.

Example16
JCode Cell
1 
2In hibernate Applications Persistence classes must be public, Non abstract and non-final.
3

1) Prepare Persistence Class or Object

columns, where names are not required to be matched, but, data types must be

compatible.

Example17
JCode Cell
1 
2In Persistence classes all Properties must be declared as per database table provided
3

1) Prepare Persistence Class or Object

methods for each and every property

Example18
JCode Cell
1 
2In Persistence classes, all properties must be declared as private in order to improveEncapsulation.
3In Persistence classes , we must define a separate set of setXXX () and getXXX ()
4

1) Prepare Persistence Class or Object

arg constructor, because, while creating object for persistence class Hibernate software will

search and execute only public and 0-arg constructor.

Example19
JCode Cell
1 
2In persistence classes, we must declare all methods are public.
3In Persistence classes, if we want to provide any constructor then it must be public and 0-
4

1) Prepare Persistence Class or Object

comparing Persistence objects then it is suggestible to Override equals(--) method.

Example20
JCode Cell
1 
2In Hibernate applications , if we want to provide our own comparison mechanisms while
3

1) Prepare Persistence Class or Object

suggestible to Overrid hashCode () method.

Example21
JCode Cell
1 
2In Hibernate applications, if we want to provide our own hash code values then it is
3

1) Prepare Persistence Class or Object

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.

Example22
JCode Cell
1 
2In Hibernate applications, we will use POJO classes, which are not extending and
3

1) Prepare Persistence Class or Object

primary key column in the respective table.

EX: Employee.java

Example23
JCode Cell
1 
2In Persistence classes, we have to declare a property as an ID property, it must represent
3

1) Prepare Persistence Class or Object

Example24
JCode Cell
1 
2public class Employee{
3private int eno;
4private String ename;
5private float esal;
6private String eaddr;
7

1) Prepare Persistence Class or Object

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 intemation 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.

Upto 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.

Example25
JCode Cell
1 
2public void setEno(int eno){
3this.eno = eno;
4}
5public void setEname(String ename){
6this.ename = ename;
7}
8public void setEsal(float esal){
9this.esal = esal;
10}
11public void setEaddr(String eaddr){
12this.eaddr = eaddr;
13}
14public int getEno(){
15return eno;
16}
17public String getEname(){
18return ename;
19}
20public float getEsal(){
21return esal;
22}
23public String getEaddr(){
24return eaddr;
25}
26}
27Prepare Mapping File:
28

1) Prepare Persistence Class or Object

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 inorder 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 inorder 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 inorder 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.

EX:

Example26
JCode Cell
1 
2<!DOCTYPE......>
3<hibernate-mapping>
4<class name="--" table="--">
5<id name="--" column="--"/>
6<property name="--" column="---"/>
7----
8</class>
9</hibernate-mapping>
10

1) Prepare Persistence Class or Object

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,........

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.

Example27
JCode Cell
1 
2<!DOCTYPE.....>
3<hibernate-mapping>
4<class name="com.durgasoft.Employee" table="emp1">
5<id name="eno" column="eno"/>
6<property name="ename"/>
7<property name="esal" column="emp_Sal"/>
8<property name="eaddr" column="eaddr"/>
9</class>
10</hibernate-mapping>
11Prepare Hibernate Configuration File:
12

1) Prepare Persistence Class or Object

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.

EX:

hibernate.cfg.xml:

Example28
JCode Cell
1 
2<!DOCTYPE....>
3<hibernate-configuration>
4<session-factory>
5<property name="--"> value </property>
6------
7------
8<mapping resource="---"/>
9-----
10</session-factory>
11</hibernate-configuration>
12

1) Prepare Persistence Class or Object

In Hibernate configurations, "dialect" is a property, it able to provide dialect class name, it is

providing the respective database native implementations which we are using in hibernate

applications in order to prepare database dependent sql queries by Hibernate software.

Hibernate has provided separate predefined class in the form of org.hibernate.dialect.XXXDialect

for each and every database.

EX: org.hibernate.dialect.Oracle9Dialect

org.hibernate.dialect.Oracle10gDialect

org.hibernate.dialect.MySQLDialect

  • 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.

  • Create Configuration class object
  • Create Session Factory object
  • Create Session Object
  • Create Transaction object if it is required.
  • Perform Persistence operations
  • Close Session Factory and Session objects.
  • 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()

EX: 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.

Example29
JCode Cell
1 
2<!DOCTYPE....>
3<hibernate-configuration>
4<session-factory>
5<property name="connection.driver_Class"> oracle.jdbc.OracleDriver
6</property>
7<property name="connection.url">
8jdbc:oracle:thin:@localhost:1521:xe
9</property>
10<property name="connection.user">system</property>
11<property name="connection.password">durga</property>
12<property name="hibernate.dialect"> org.hibernate.dialect.OracleDialect
13</property>
14<mapping resource="Employee.hbm.xml"/>
15</session-factory>
16</hibernate-configuration>
17

1) Prepare Persistence Class or Object

This method will get configuration details from the configuration file with the name

hibernate.cfg.xml

Example30
JCode Cell
1 
2public Configuration configure()
3

1) Prepare Persistence Class or Object

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 .

Example31
JCode Cell
1 
2public Configuration configure(String config_file_Name)
3

1) Prepare Persistence Class or Object

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 .

EX: 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.

  • Create Session Factory object:

In Hibernate, the main intention of Session Factory object is to manage Connections, Statements,

Cache levels, .... 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()

EX: SessionFactory sf = cfg.buildSessionFactory();

Note: The above approach to get Session Factory object is available upto Hibernate3.x version,

buildSessionFactory() was deprecated in Hibernate4.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 upto a particular Database, because,

it able to allow more than one thread at a time.

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

EX: 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.

  • 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.

Example32
JCode Cell
1 
2public Configuration configure(File file)
3

1) Prepare Persistence Class or Object

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

following method.

public void begin()

Example33
JCode Cell
1 
2public Transaction getTransaction()
3

1) Prepare Persistence Class or Object

It will return Transaction and begin Transaction.

In Hibernate applications, after performing persistence operations we must perform either commit

or rollback operations inorder 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.

  • 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.

Example34
JCode Cell
1 
2public Transaction beginTransaction()
3

1) Prepare Persistence Class or Object

What is the difference between save() method and persist() method?

Answer:

In Hibernate applications, save() method can be used to insert a record into the Database table

and it will retuen Primary Key value of the inserted record.

public Serializable save(Object obj)throws HibernateException

In Hibernate applications, persist() method can be used to insert a record into database table and

it will not return any value.

public void persist(Object obj)throws HibernateException

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

Example35
JCode Cell
1 
2save(--)
3persist(--)
4

1) Prepare Persistence Class or Object

What is the difference between update() method and saveOrUpdate() method?

Answer:

Where update(-) method will perform updation on a record in database table if the specified record

is existed otherwise it will rise an Exception.

public void update(Object obj)throws HibernateException

Where saveOrUpdate(-) method will insert the specified record in database table if the specified

record is not existed . If the specified record is existed in database table then it will update the

record.

public void saveOrUpdate(Object obj)throws HibernateException

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

public void delete(Object obj) throws HibernateException

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

1.get(--)

2.load(--)

What are the differences between get(-) method and load(-) method?

Answer:

  • get() method can be used to retrive a record from database table if the record is existed. If the

required record is not existed then get() method will return null value.

public Object get(String class_Name, Serializable pk_Val)

public Object get(Class class_Type, Serializable pk_Val)

load() method can be used to retgrive a record from database table if the record is existed. If the

required record is not existed then load() method will rise an Exception like HibernateException.

public Object load(String class_Name, Serializable pk_Val)

public Object load(Class class_Type, Serializable pk_val)

  • get() method is able to perform eager or early loading, that is, it will interact with database

directly and it will retrive data and return to Hibernate application in the form of Object on the

method call.

load() method will perform Lazy or late Loading , that is, when we access load() method then a

duplicate object will be created with the primary key value without interacting with database. When

we use other properties of the Object then only it will fetch data from database table and return

that data to Java application.

  • 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.

EX: s.close();

sf.close();

Hibernate Applications with Eclipse

Eclipse:

Example36
JCode Cell
1 
2update(--)
3saveOrUpdate(--)
4

1) Prepare Persistence Class or Object

i. Eclipse4.3.1[26 june,2013][Kepler]

ii. Eclipse4.4[9th Aug,2013][Luna]

iii. Eclipse4.5[Mars]

iv. Eclipse4.6[Neon]

v. Eclipse4.7[Oxygen]

  • Designed on: Java platform.
  • Type: Open Source Software.
Example37
JCode Cell
1 
2Home: IBM canada [Initially]
3Eclipse Foundations [2003]
4website: www.eclipse.org
5Objective: To simplify JAVA/J2EE application Development.
6Initial Version: Ecplise3.0[2004]
7Used Versions:Eclipse3.5,3.6,3.7[Helios,Gelilio,Indigo]
8Latest Version: Ecplise4.2[1st march,2013][JUNO]
9
📝 Key Takeaways
  • Key ideas of Hibernate - Introduction explained simply
  • Ready-to-use code examples
  • Exam-style questions at the end

🧠 Test Your Knowledge

8 Questions
Progress: 0 / 8