Hibernate
Hibernate
Hibernate is an Object-Relational Mapping (ORM) framework for Java that facilitates the mapping of Java
objects to database tables. It abstracts the complexities of database interactions, allowing developers to
work with high-level object-oriented programming concepts instead of low-level SQL queries. Hibernate
manages the persistence of data, enabling CRUD (Create, Read, Update, Delete) operations seamlessly.
Key Uses of Hibernate
1. Data Persistence:
Hibernate simplifies the process of storing Java objects in a relational database, handling
the conversion between the two seamlessly.
2. Database Independence:
It allows applications to be database-agnostic, meaning they can easily switch databases
without significant code changes.
3. Simplified Database Operations:
Developers can perform complex database operations using simple Java methods,
reducing the need for extensive SQL.
4. Transaction Management:
Hibernate provides built-in support for managing transactions, ensuring data integrity
and consistency.
5. Caching Mechanism:
It offers first-level and second-level caching to improve application performance by
reducing direct database access.
6. Lazy Loading:
Hibernate supports lazy loading, which means that related data is fetched only when it is
accessed, optimizing resource usage.
7. Querying with HQL:
Hibernate Query Language (HQL) allows developers to write database queries in an
object-oriented way, making queries more intuitive.
8. Change Tracking:
It automatically tracks changes made to persistent objects, simplifying the update
process.
9. Support for Inheritance:
Hibernate provides support for mapping inheritance hierarchies, allowing for more
complex data models.
10. Integration with Java EE:
Hibernate integrates well with Java EE technologies, such as JPA (Java Persistence API),
making it suitable for enterprise applications.
Advantages of Hibernate over JDBC:
1. Object-Relational Mapping (ORM):
Hibernate allows developers to work with objects rather than SQL queries, making it
easier to manage data as Java objects.
2. Database Independence:
Hibernate abstracts the underlying database, allowing for easier migration between
different database systems without major code changes.
3. Automatic Table Generation:
Hibernate can automatically generate database tables based on the entity classes,
reducing the need for manual SQL scripts.
4. Caching:
Hibernate supports first-level and second-level caching, which can significantly improve
performance by reducing database access.
5. Lazy Loading:
It supports lazy loading of data, meaning related data is loaded only when accessed,
improving initial load times and resource usage.
6. Transaction Management:
Hibernate provides built-in support for transaction management, making it easier to
handle complex transactions.
7. Query Language:
Hibernate Query Language (HQL) is more powerful and expressive than SQL, allowing for
easier querying of object data.
8. Change Tracking:
Hibernate automatically tracks changes to objects, simplifying the process of updating
the database
Need of Hibernate Framework
Hibernate is used to overcome the limitations of JDBC like:
1. JDBC code is dependent upon the Database software being used i.e. our persistence logic is
dependent, because of using JDBC. Here we are inserting a record into Employee table but our
query is Database software-dependent i.e. Here we are using MySQL. But if we change our
Database then this query won’t work.
2. If working with JDBC, changing of Database in middle of the project is very costly.
3. JDBC code is not portable code across the multiple database software.
4. In JDBC, Exception handling is mandatory. Here We can see that we are handling lots of
Exception for connection.
5. While working with JDBC, There is no support Object-level relationship.
6. In JDBC, there occurs a Boilerplate problem i.e. For each and every project we have to write the
below code. That increases the code length and reduce the readability.
To overcome the above problems we use ORM tool i.e. nothing but Hibernate framework. By using
Hibernate we can avoid all the above problems and we can enjoy some additional set of functionalities.
About Hibernate Framework
Hibernate is a framework which provides some abstraction layer, meaning that the programmer does
not have to worry about the implementations, Hibernate does the implementations for you internally
like Establishing a connection with the database, writing query to perform CRUD operations etc.
It is a java framework which is used to develop persistence logic. Persistence logic means to store and
process the data for long use. More precisely Hibernate is an open-source, non-invasive, light-weight
java ORM(Object-relational mapping) framework to develop objects which are independent of the
database software and make independent persistence logic in all JAVA, JEE.
Framework means it is special install-able software that provides an abstraction layer on one or more
technologies like JDBC, Servlet, etc to simplify or reduce the complexity for the development process.
Open Source means:
Hibernate framework is available for everyone without any cost.
The source code of Hibernate is also available on the Internet and we can also modify the code.
Light-weight means:
Hibernate is less in size means the installation package is not big is size.
Hibernate does not require any heavy container for execution.
It does not require POJO and POJI model programming.
Hibernate can be used alone or we can use Hibernate with other java technology and
framework.
Non-invasive means:
The classes of Hibernate application development are loosely coupled classes with respect to
Hibernate API i.e. Hibernate class need not implement hibernate API interfaces and need not
extend from Hibernate API classes.
Functionalities supported by Hibernate framework
Hibernate framework support Auto DDL operations. In JDBC manually we have to create table
and declare the data-type for each and every column. But Hibernate can do DDL operations for
you internally like creation of table,drop a table,alter a table etc.
Hibernate supports Auto Primary key generation. It means in JDBC we have to manually set a
primary key for a table. But Hibernate can this task for you.
Hibernate framework is independent of Database because it supports HQL (Hibernate Query
Language) which is not specific to any database, whereas JDBC is database dependent.
In Hibernate, Exception Handling is not mandatory, whereas In JDBC exception handling is
mandatory.
Hibernate supports Cache Memory whereas JDBC does not support cache memory.
Hibernate is a ORM tool means it support Object relational mapping. Whereas JDBC is not object
oriented moreover we are dealing with values means primitive data. In hibernate each record is
represented as a Object but in JDBC each record is nothing but a data which is nothing but
primitive values.
ORM[
Hibernate is an Object-Relational Mapping (ORM) solution for JAVA. It is an open source persistent
framework created by Gavin King in 2001. It is a powerful, high performance Object-Relational
Persistence and Query service for any Java Application.
Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieves
the developer from 95% of common data persistence related programming tasks.
Hibernate sits between traditional Java objects and database server to handle all the works in persisting
those objects based on the appropriate O/R mechanisms and patterns.
Hibernate Advantages
Hibernate takes care of mapping Java classes to database tables using XML files and without
writing any line of code.
Provides simple APIs for storing and retrieving Java objects directly to and from the database.
If there is change in the database or in any table, then you need to change the XML file
properties only.
Abstracts away the unfamiliar SQL types and provides a way to work around familiar Java
Objects.
Hibernate does not require an application server to operate.
Manipulates Complex associations of objects of your database.
Minimizes database access with smart fetching strategies.
Provides simple querying of data.
Supported Databases
Hibernate supports almost all the major RDBMS. Following is a list of few of the database engines
supported by Hibernate −
HSQL Database Engine
DB2/NT
MySQL
PostgreSQL
FrontBase
Oracle
Microsoft SQL Server Database
Sybase SQL Server
Informix Dynamic Server
Supported Technologies
Hibernate supports a variety of other technologies, including −
XDoclet Spring
J2EE
Eclipse plug-ins
Maven
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified
expert to boost your career.
Hibernate Prerequisites
Following is the list of packages/libraries required by Hibernate and you should install them before
starting with Hibernate. To install these packages, you will have to copy library files from /lib into your
CLASSPATH, and change your CLASSPATH variable accordingly.
Sr.No. Packages/Libraries
MySQL Connector/J
1
MySQL Driver https://dev.mysql.com/downloads/connector/j/
Java EE
2
Java EE API J2EE API
dom4j
1
XML parsing www.dom4j.org/
Xalan
2
XSLT Processor https://xml.apache.org/xalan-j/
Xerces
3
The Xerces Java Parser https://xml.apache.org/xerces-j/
Cglib
4
Appropriate changes to Java classes at runtime http://cglib.sourceforge.net/
log4j
5
Logging Faremwork https://logging.apache.org/log4j
Commons
6
Logging, Email etc. https://jakarta.apache.org/commons
SLF4J
7
Logging Facade for Java https://www.slf4j.org
Hibernate - Configuration
Hibernate requires to know in advance — where to find the mapping information that defines how your
Java classes relate to the database tables. Hibernate also requires a set of configuration settings related
to database and other related parameters. All such information is usually supplied as a standard Java
properties file called hibernate.properties, or as an XML file named hibernate.cfg.xml.
I will consider XML formatted file hibernate.cfg.xml to specify required Hibernate properties in my
examples. Most of the properties take their default values and it is not required to specify them in the
property file unless it is really required. This file is kept in the root directory of your application's
classpath.
Hibernate Properties
Following is the list of important properties, you will be required to configure for a databases in a
standalone situation −
Sr.No. Properties & Description
hibernate.dialect
1 This property makes Hibernate generate the appropriate SQL for the chosen
database.
hibernate.connection.driver_class
2
The JDBC driver class.
hibernate.connection.url
3
The JDBC URL to the database instance.
hibernate.connection.username
4
The database username.
hibernate.connection.password
5
The database password.
hibernate.connection.pool_size
6 Limits the number of connections waiting in the Hibernate database
connection pool.
hibernate.connection.autocommit
7
Allows autocommit mode to be used for the JDBC connection.
hibernate.cfg.xml
Hibernate with MySQL Database
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.3//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/lak</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping class="com.bluecrest.FirstAPP.Student"></mapping>
</session-factory>
</hibernate-configuration>
DAO.JAVA
The entire concept of Hibernate is to take the values from Java class attributes and persist them to a
database table. A mapping document helps Hibernate in determining how to pull the values from the
classes and map them with table and associated fields.
Java classes whose objects or instances will be stored in database tables are called persistent classes in
Hibernate. Hibernate works best if these classes follow some simple rules, also known as the Direct
Access Object (DAO) programming model.
There are following main rules of persistent classes, however, none of these rules are hard requirements
−
All Java classes that will be persisted need a default constructor.
All classes should contain an ID in order to allow easy identification of your objects within
Hibernate and the database. This property maps to the primary key column of a database table.
All attributes that will be persisted should be declared private and
have getXXX and setXXX methods defined in the JavaBean style.
A central feature of Hibernate, proxies, depends upon the persistent class being either non-final,
or the implementation of an interface that declares all public methods.
All classes that do not extend or implement some specialized classes and interfaces required by
the EJB framework.
The POJO name is used to emphasize that a given object is an ordinary Java Object, not a special object,
and in particular not an Enterprise JavaBean.
DAO.JAVA
package com.bluecrest.FirstAPP;
import javax.persistence.*;
@Entity
@Table
public class Student {
@Id
@GeneratedValue
private int id;
private String 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;
}
}
Hibernate - Sessions
A Session is used to get a physical connection with a database. The Session object is lightweight and
designed to be instantiated each time an interaction is needed with the database. Persistent objects are
saved and retrieved through a Session object.
The session objects should not be kept open for a long time because they are not usually thread safe and
they should be created and destroyed them as needed. The main function of the Session is to offer,
create, read, and delete operations for instances of mapped entity classes.
Instances may exist in one of the following three states at a given point in time −
transient − A new instance of a persistent class, which is not associated with a Session and has
no representation in the database and no identifier value is considered transient by Hibernate.
persistent − You can make a transient instance persistent by associating it with a Session. A
persistent instance has a representation in the database, an identifier value and is associated
with a Session.
detached − Once we close the Hibernate Session, the persistent instance will become a
detached instance.
A Session instance is serializable if its persistent classes are serializable. A typical transaction should use
the following idiom −
package com.bluecrest.FirstAPP;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
If the Session throws an exception, the transaction must be rolled back and the session must be
discarded.
Session Interface Methods
There are number of methods provided by the Session interface, but I'm going to list down a few
important methods only, which we will use in this tutorial. You can check Hibernate documentation for a
complete list of methods associated with Session and SessionFactory.
Sr.No. Session Methods & Description
Transaction beginTransaction()
1
Begin a unit of work and return the associated Transaction object.
void cancelQuery()
2
Cancel the execution of the current query.
void clear()
3
Completely clear the session.
Connection close()
4
End the session by releasing the JDBC connection and cleaning up.
SessionFactory getSessionFactory()
14
Get the session factory which created this session.
void refresh(Object object)
15
Re-read the state of the given instance from the underlying database.
Transaction getTransaction()
16
Get the Transaction instance associated with this session.
boolean isConnected()
17
Check if the session is currently connected.
boolean isDirty()
18 Does this session contain any changes which must be synchronized with the
database?
boolean isOpen()
19
Check if the session is still open.
Hibernate - Annotations
@Entity Annotation
The EJB 3 standard annotations are contained in the javax.persistence package, so we import this
package as the first step. Second, we used the @Entity annotation to the Employee class, which marks
this class as an entity bean, so it must have a no-argument constructor that is visible with at least
protected scope.
@Table Annotation
The @Table annotation allows you to specify the details of the table that will be used to persist the
entity in the database.
The @Table annotation provides four attributes, allowing you to override the name of the table, its
catalogue, and its schema, and enforce unique constraints on columns in the table. For now, we are
using just table name, which is EMPLOYEE.
@Id and @GeneratedValue Annotations
Each entity bean will have a primary key, which you annotate on the class with the @Id annotation. The
primary key can be a single field or a combination of multiple fields depending on your table structure.
By default, the @Id annotation will automatically determine the most appropriate primary key
generation strategy to be used but you can override this by applying the @GeneratedValue annotation,
which takes two parameters strategy and generator that I'm not going to discuss here, so let us use only
the default key generation strategy. Letting Hibernate determine which generator type to use makes your
code portable between different databases.
@Column Annotation
The @Column annotation is used to specify the details of the column to which a field or property will be
mapped. You can use column annotation with the following most commonly used attributes −
name attribute permits the name of the column to be explicitly specified.
length attribute permits the size of the column used to map a value particularly for a String
value.
nullable attribute permits the column to be marked NOT NULL when the schema is generated.
unique attribute permits the column to be marked as containing only unique values.
Example:
package com.bluecrest.FirstAPP;
import javax.persistence.*;
@Entity
@Table
public class Student {
@Id
@GeneratedValue
private int id;
private String name;
</session-factory>
</hibernate-configuration>
Align.java
import javax.persistence.Column;
import javax.persistence.Table;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
@Table(name="stud")
public class Align {
public int getAid() {
return aid;
}
public void setAid(int aid) {
this.aid = aid;
}
public String getAname() {
return aname;
}
public void setAname(String aname) {
this.aname = aname;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Id
private int aid;
private String aname;
}
DAO.JAVA [App.java]
package com.bluecrest.FirstAPP;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class App
{
public static void main(String args[])
{
Align s=new Align();
s.setAid(103);
s.setAname("wwww");
s.setColor("green");
Configuration configuration=new Configuration();
configuration.configure();
ServiceRegistry sr= new
ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
SessionFactory sf=configuration.buildSessionFactory(sr);
Session ss=sf.openSession();
ss.beginTransaction();
//saving objects to session
ss.save(s);
ss.getTransaction().commit();
ss.close();
}
}
</session-factory>
</hibernate-configuration>
Align.java
import javax.persistence.Column;
import javax.persistence.Table;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
@Table(name="stud")
public class Align {
public int getAid() {
return aid;
}
public void setAid(int aid) {
this.aid = aid;
}
public String getAname() {
return aname;
}
public void setAname(String aname) {
this.aname = aname;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Id
private int aid;
private String aname;
App.java
public class App
{
public static void main(String args[])
{
Align s=new Align();
s.setAid(106);
s.setAname("wwww");
s.setColor("green");
Session ss=sf.openSession();
ss.beginTransaction();
//saving objects to session
ss.save(s);
ss.getTransaction().commit();
ss.close();
}
}
import javax.persistence.Column;
import javax.persistence.Table;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
@Table(name="stud")
public class Align {
public int getAid() {
return aid;
}
public void setAid(int aid) {
this.aid = aid;
}
public String getAname() {
return aname;
}
public void setAname(String aname) {
this.aname = aname;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return "Align [aid=" + aid + ", aname=" + aname + ", color=" + color + "]";
}
@Id
private int aid;
private String aname;
App.java
Session ss=sf.openSession();
Transaction tx= ss.beginTransaction();
s=(Align)ss.get(Align.class,105);
ss.delete(s);
tx.commit();
ss.close();
Session ss=sf.openSession();
Transaction tx= ss.beginTransaction();
s=(Align)ss.get(Align.class,106);
s.setAname("lakww");
s.setColor("greenwww");
ss.save(s);
tx.commit();
ss.close();
}
}
Generators
Hibernate provides several types of ID generators that you can use to generate primary keys for your
entities. Here are the main types of ID generators available in Hibernate:
1. AUTO
Description: The persistence provider (Hibernate) picks an appropriate strategy for the particular
database.
Usage:
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
2. IDENTITY
Description: The database generates a unique identifier automatically when a new row is
inserted. This is commonly used with databases that support auto-increment columns.
Usage:
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
3. SEQUENCE
Description: Uses a database sequence to generate unique identifiers. This is efficient and works
well with databases that support sequences (e.g., PostgreSQL, Oracle).
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_seq")
@SequenceGenerator(name = "user_seq", sequenceName = "user_sequence", allocationSize = 1)
private Long id;
4. TABLE
Description: Uses a table to generate unique identifiers. This is a more portable option but can
be less efficient than sequences.
Usage:
@GeneratedValue(strategy = GenerationType.TABLE, generator = "user_table")
@TableGenerator(name = "user_table", table = "id_generator", pkColumnName = "gen_name",
valueColumnName = "gen_value", allocationSize = 1)
private Long id;
1. AUTO
App.java
package com.bluecrest;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
Session ss=sf.openSession();
ss.beginTransaction();
//saving objects to session
ss.save(s);
ss.getTransaction().commit();
ss.close();
}
}
Align.java
package com.bluecrest;
import javax.persistence.Column;
import javax.persistence.Table;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
@Table(name="lak")
public class Align {
public int getAid() {
return aid;
}
public void setAid(int aid) {
this.aid = aid;
}
public String getAname() {
return aname;
}
public void setAname(String aname) {
this.aname = aname;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Id
}
Table:
CREATE TABLE `lak` (
`aid` int NOT NULL auto_increment ,
`aname` varchar(45) DEFAULT NULL,
`color` varchar(45) DEFAULT NULL,primary key(aid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/lak</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping class="com.bluecrest.Align"/>
</session-factory>
</hibernate-configuration>
App.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
Session ss=sf.openSession();
ss.beginTransaction();
//saving objects to session
ss.save(s);
ss.getTransaction().commit();
ss.close();
}
}
Align.java
import javax.persistence.Column;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
@Table(name="lak")
public class Align {
public int getAid() {
return aid;
}
public void setAid(int aid) {
this.aid = aid;
}
public String getAname() {
return aname;
}
public void setAname(String aname) {
this.aname = aname;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Id
Caching in Hibernate
1. Caching in Hibernate
2. First Level Cache
3. Second Level Cache
Hibernate caching improves the performance of the application by pooling the object in the cache. It is
useful when we have to fetch the same data multiple times.
There are mainly two types of caching:
o First Level Cache, and
o Second Level Cache
First Level Cache
Session object holds the first level cache data. It is enabled by default. The first level cache data will not
be available to entire application. An application can use many session object.
Second Level Cache
SessionFactory object holds the second level cache data. The data stored in the second level cache will
be available to entire application. But we need to enable it explicitely.
public Employee() {}
public Employee(String name, float salary) {
super();
this.name = name;
this.salary = salary;
}
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 float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
}
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
<version>10.2.0.4.0</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.3</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>5.2.16.Final</version>
</dependency>
<hibernate-configuration>
<session-factory>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">jtp</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="cache.use_second_level_cache">true</property>
<property name="cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFac
tory</property>
<mapping class="com.javatpoint.Employee"/>
</session-factory>
</hibernate-configuration>
To implement second level cache, we need to define cache.provider_class property in the configuration
file.
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
SessionFactory factory=meta.getSessionFactoryBuilder().build();
Session session1=factory.openSession();
Employee emp1=(Employee)session1.load(Employee.class,121);
System.out.println(emp1.getId()+" "+emp1.getName()+" "+emp1.getSalary());
session1.close();
Session session2=factory.openSession();
Employee emp2=(Employee)session2.load(Employee.class,121);
System.out.println(emp2.getId()+" "+emp2.getName()+" "+emp2.getSalary());
session2.close();
}
}