Module 4
Module 4
HIBERNATE FRAMEWORK
STRUCTURE:
[Link] Objectives
[Link] Framework
[Link] Implementation :
[Link] :
[Link] SQL :
Hibernate is a Java framework that simplifies the development of Java application to interact
with the database. It is an open source, lightweight, ORM (Object Relational Mapping) tool.
Hibernate implements the specifications of JPA (Java Persistence API) for data persistence.
ORM Tool
An ORM tool simplifies the data creation, data manipulation and data access. It is a
programming technique that maps the object to the data stored in the database.
The ORM tool internally uses the JDBC API to interact with the database.
What is JPA?
Java Persistence API (JPA) is a Java specification that provides certain functionality and
standard to ORM tools. The [Link] package contains the JPA classes and
interfaces.
38
Advantages of Hibernate Framework
Hibernate framework is open source under the LGPL license and lightweight.
2) Fast Performance
The performance of hibernate framework is fast because cache is internally used in hibernate
framework. There are two types of cache in hibernate framework first level cache and second
level cache. First level cache is enabled by default.
HQL (Hibernate Query Language) is the object-oriented version of SQL. It generates the
database independent queries. So you don't need to write database specific queries. Before
Hibernate, if database is changed for the project, we need to change the SQL query as well that
leads to the maintenance problem.
Hibernate framework provides the facility to create the tables of the database automatically. So
there is no need to create tables in the database manually.
Hibernate supports Query cache and provide statistics about query and database status.
o Database layer
39
Let's see the diagram of hibernate architecture:
40
This is the high level architecture of Hibernate with mapping file and configuration file
Hibernate framework uses many objects such as session factory, session, transaction etc. along
with existing Java API such as JDBC (Java Database Connectivity), JTA (Java Transaction
API) and JNDI (Java Naming Directory Interface).
For creating the first hibernate application, we must know the elements of Hibernate architecture.
41
Session Factory
The Session Factory is a factory of session and client of Connection Provider. It holds second
level cache (optional) of data. The [Link] Factory interface provides factory
method to get the object of Session.
Session
The session object provides an interface between the application and data stored in the
database. It is a short-lived object and wraps the JDBC connection. It is factory of Transaction,
Query and Criteria. It holds a first-level cache (mandatory) of data. The [Link]
interface provides methods to insert, update and delete the object. It also provides factory
methods for Transaction, Query and Criteria.
Transaction
The transaction object specifies the atomic unit of work. It is optional. The
[Link] interface provides methods for transaction management.
Connection Provider
It is a factory of JDBC connections. It abstracts the application from Driver Manager or Data
Source. It is optional.
Transaction Factory
1. Transient State
2. Persistent State
3. Detached State
4. Removed State
42
State 1: Transient State
The transient state is the first state of an entity object. When we instantiate an object of
a POJO class using the new operator then the object is in the transient state. This object is
not connected with any hibernate session. As it is not connected to any Hibernate Session,
So this state is not connected to any database table. So, if we make any changes in the data
of the POJO Class then the database table is not altered. Transient objects are independent of
Hibernate, and they exist in the heap memory.
There are two layouts in which transient state will occur as follows:
1. When objects are generated by an application but are not connected to any
session.
Here, we are creating a new object for the Employee class. Below is the code which shows
the initialization of the Employee object :
[Link](21);
[Link]("Neha");
[Link]("Shri");
43
[Link]("Rudra");
Once the object is connected with the Hibernate Session then the object moves into the
Persistent State. So, there are two ways to convert the Transient State to the Persistent State
:
1. Using the hibernated session, save the entity object into the database table.
2. Using the hibernated session, load the entity object into the database table.
In this state. each object represents one row in the database table. Therefore, if we make
any changes in the data then hibernate will detect these changes and make changes in the
database table.
• [Link](e);
• [Link](e);
• [Link](e);
• [Link](e);
• [Link](e);
• [Link](e);
Example:
44
//Persistent State
[Link](e);
For converting an object from Persistent State to Detached State, we either have to close the
session or we have to clear its cache. As the session is closed here or the cache is cleared,
then any changes made to the data will not affect the database table. Whenever needed, the
detached object can be reconnected to a new hibernate session. To reconnect the detached
object to a new hibernate session, we will use the following methods as follows:
• merge()
• update()
• load()
• refresh()
• [Link](e);
• [Link](e);
• [Link]();
• [Link]();
Example
// Transient State
// Persistent State
[Link](e);
45
// Detached State
[Link]();
In the hibernate lifecycle it is the last state. In the removed state, when the entity object is
deleted from the database then the entity object is known to be in the removed state. It is
done by calling the delete() operation. As the entity object is in the removed state, if any
change will be done in the data will not affect the database table.
Example
// Transient State
Session s = [Link]();
[Link](01);
// Persistent State
[Link](e)
// Removed State
[Link](e);
46
persistent Classes :
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 Plain Old Java Object (POJO) programming model.
There are following main rules of persistent classes, however, none of these rules are hard
requirements −
• 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.
• 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.
Based on the few rules mentioned above, we can define a POJO class as follows −
47
public Employee() {}
[Link] = fname;
[Link] = lname;
[Link] = salary;
return id;
[Link] = id;
return firstName;
[Link] = first_name;
return lastName;
48
public void setLastName( String last_name ) {
[Link] = last_name;
return salary;
[Link] = salary;
[Link] Implementation :
Spring MVC is a popular model view controller framework that handles dependency
injection at run time. Hibernate 5 is an ORM framework that acts as an abstraction over the
database. It allows interaction with the underlying database by removing any implementation
details which is handled by hibernate. In this article, we will integrate Spring MVC and
Hibernate 5 with an in-memory database h2.
Requirements
• Maven
• Java 8+
49
Required Dependencies
After creating an empty project you will need some core dependencies which are required
for a bootstrap setup. In the dependencies section of your [Link] add the following
dependencies
spring-orm
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-orm</artifactId>
<version>[Link]</version>
</dependency>
hibernate-core
• XML
• <dependency>
• <groupId>[Link]</groupId>
• <artifactId>hibernate-core</artifactId>
• <version>[Link]</version>
• </dependency>
h2-database
In-memory database
• XML
50
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
</dependency>
commons-dbcp2
<dependency>
<groupId>[Link]</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.7.0</version>
</dependency>
lombok
• XML
<dependency>
<groupId>[Link]</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
51
Configuration
[Link] file will contain the basic configurations of the database we will read this source
to configure our hibernate session
# MySQL properties
[Link]=[Link]
[Link]=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
[Link]=sa
[Link]=sa
# Hibernate properties
[Link]=create-drop
[Link]=[Link].H2Dialect
Create a configuration class to wire the details for hibernate and set up the session factory
etc
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
52
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@EnableTransactionManagement
@Configuration
@PropertySource("classpath:[Link]")
@Autowired
@Bean
[Link](dataSource());
[Link](
new String[]{"[Link]"});
[Link](hibernateProperties());
return sessionFactory;
@Bean
53
public DataSource dataSource() {
[Link]([Link]("[Link]"));
[Link]([Link]("[Link]"));
[Link]([Link]("[Link]"));
[Link]([Link]("[Link]"));
return dataSource;
@Bean
HibernateTransactionManager transactionManager
= new HibernateTransactionManager();
[Link](sessionFactory().getObject());
return transactionManager;
[Link](
"[Link]", [Link]("[Link]"));
[Link](
"[Link]", [Link]("[Link]"));
return hibernateProperties;
• Java
54
package [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;
@AllArgsConstructor
@NoArgsConstructor
@Data
@Entity
@Table(name = "user")
@Id
@GeneratedValue(strategy = [Link])
@Column(name = "id")
@Column(name = "first_name")
@Column(name = "last_name")
55
Repository class
• Java
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Repository
@Autowired
[Link]().save(user);
Service class
56
• Java
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Service
@RequiredArgsConstructor
@Autowired
@Transactional
[Link](user);
@Transactional
57
return [Link](id);
Application class
This is the entry point of the application, we need to wire this configuration to the application
context.
package example;
import [Link];
import [Link];
import [Link];
[Link]("Starting application");
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext([Link]);
[Link]([Link]());
58
}
Output:
Hibernate: create table user (id integer generated by default as identity, first_name
varchar(255), last_name varchar(255), primary key (id))
59
Package Structure :
Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but
instead of operating on tables and columns, HQL works with persistent objects and their
properties. HQL queries are translated by Hibernate into conventional SQL queries, which in
turns perform action on database.
60
Although you can use SQL statements directly with Hibernate using Native SQL, but I would
recommend to use HQL whenever possible to avoid database portability hassles, and to take
advantage of Hibernates SQL generation and caching strategies.
Keywords like SELECT, FROM, and WHERE, etc., are not case sensitive, but properties like
table and column names are case sensitive in HQL.
FROM Clause
You will use FROM clause if you want to load a complete persistent objects into memory.
Following is the simple syntax of using FROM clause −
If you need to fully qualify a class name in HQL, just specify the package and class name as
follows −
AS Clause
The AS clause can be used to assign aliases to the classes in your HQL queries, especially when
you have the long queries. For instance, our previous simple example would be the following
−
The AS keyword is optional and you can also specify the alias directly after the class name, as
follows −
61
List results = [Link]();
SELECT Clause
The SELECT clause provides more control over the result set then the from clause. If you want
to obtain few properties of objects instead of the complete object, use the SELECT clause.
Following is the simple syntax of using SELECT clause to get just first_name field of the
Employee object −
It is notable here that [Link] is a property of Employee object rather than a field
of the EMPLOYEE table.
WHERE Clause
If you want to narrow the specific objects that are returned from storage, you use the WHERE
clause. Following is the simple syntax of using WHERE clause −
ORDER BY Clause
To sort your HQL query's results, you will need to use the ORDER BY clause. You can order
the results by any property on the objects in the result set either ascending (ASC) or descending
(DESC). Following is the simple syntax of using ORDER BY clause −
String hql = "FROM Employee E WHERE [Link] > 10 ORDER BY [Link] DESC";
If you wanted to sort by more than one property, you would just add the additional properties
to the end of the order by clause, separated by commas as follows −
62
"ORDER BY [Link] DESC, [Link] DESC ";
GROUP BY Clause
This clause lets Hibernate pull information from the database and group it based on a value of
an attribute and, typically, use the result to include an aggregate value. Following is the simple
syntax of using GROUP BY clause −
"GROUP BY [Link]";
2. Criteria Interface
3. Restrictions class
4. Examples of HCQL
The Hibernate Criteria Query Language (HCQL) is used to fetch the records based on the
specific criteria. The Criteria interface provides methods to apply criteria such as retreiving all
the records of table whose salary is greater than 50000 etc.
Advantage of HCQL
The HCQL provides methods to add criteria, so it is easy for the java programmer to add
criteria. The java programmer is able to add many criteria on a query.
63
Criteria Interface
The Criteria interface provides many methods to specify criteria. The object of Criteria can be
obtained by calling the create Criteria() method of Session interface.
3. public Criteria setFirstResult(int first Result) specifies the first number of record to be
retrieved.
4. public Criteria somersault(int total Result) specifies the total number of records to be
retrieved.
Restrictions class
Restrictions class provides methods that can be used as Criterion. The commonly used methods
of Restrictions class are as follows:
2. public static SimpleExpression le(String propertyName,Object value) sets the less than
or equal constraint to the given property.
64
7. public static Criterion between(String propertyName, Object low, Object high) sets
the between constraint.
Order class
The Order class represents an order. The commonly used methods of Restrictions class are as
follows:
1. public static Order asc(String propertyName) applies the ascending order on the basis
of given property.
2. public static Order desc(String propertyName) applies the descending order on the
basis of given property.
2. List list=[Link]();
1. Crietria c=[Link]([Link]);
2. [Link](10);
3. [Link](20);
4. List list=[Link]();
Example of HCQL to get the records whose salary is greater than 10000
1. Crietria c=[Link]([Link]);
3. List list=[Link]();
65
Example of HCQL to get the records in ascending order on the basis of salary
1. Crietria c=[Link]([Link]);
2. [Link]([Link]("salary"));
3. List list=[Link]();
We can fetch data of a particular column by projection such as name etc. Let's see the simple
example of projection that prints data of NAME column of the table only.
1. Criteria c=[Link]([Link]);
2. [Link]([Link]("name"));
3. List list=[Link]();
Mapping Types :
1. Primitive Types
4. JDK-related Types
So, let us discuss each of the above 4 listed mapping types in detail as follows:
A. Primitive Types
These types of mapping have data types defined as “integer”, “character”, “float”, “string”,
“double”, “Boolean”, “short”, “long” etc. These are present in hibernate framework to map
java data type to RDBMS data type.
66
Mapping Type Java Type ANSI SQL Type
These are “date”, “time”, “calendar”, “timestamp” etc. Like primitive we have these date
and time datatype mappings.
67
Mapping type Java type ANSI SQL Type
These types are “clob”, “blob”, “binary”, “text” etc. Clob and blob data types are present to
maintain the data type mapping of large objects like images and videos.
Mapping
type Java type ANSI SQL Type
VARBINARY (or
binary byte[] BLOB)
68
Mapping
type Java type ANSI SQL Type
D. JDK linked
Some of the mappings for objects which lie beyond the reach of the previous type of
mappings are included in this category. These are “class”, “locale”, “currency”,
“timezone”.
4.5. ANNOTATIONS :
Generally, in hibernate, we use XML mapping files for converting our POJO classes data to
database data and vice-versa. But using XML becomes a little confusing so, in replacement
of using XML, we use annotations inside our POJO classes directly to declare the changes.
Also using annotations inside out POJO classes makes things simple to remember and easy
to use. Annotation is a powerful method of providing metadata for the database tables and
69
also it gives brief information about the database table structure and also POJO classes
simultaneously.
It’s recommended to set up the Maven project for hibernate because it becomes easy to
copy-paste dependency from the official Maven repository into your [Link].
After setting up a maven project, by default, you get a [Link] file which is a dependency
file. POM stands for project object model, which allows us to add or remove dependency
from 1 location. Now, add hibernate and MySQL dependency to use annotations to create a
table and to use HQL(hibernate query language).
We use the [Link] file to provide all related database parameters like database
username, password, localhost, etc. Make sure you make the [Link] inside
the resource folder
[Link]
Step 4: Add POJO and main classes for working with the functionality
Here are some annotations used in our POJO specifically for hibernate-
@Entity Used for declaring any POJO class as an entity for a database
70
Annotations Use of annotations
• schema
• catalogue
Step 4: Add POJO and main classes for working with the functionality
Here are some annotations used in our POJO specifically for hibernate-
@Entity Used for declaring any POJO class as an entity for a database
• schema
• catalogue
71
It is used to specify column mappings. It means if in case we don’t
need the name of the column that we declare in POJO but we need
to refer to that entity you can change the name for the database
table. Some attributes are-
Used to tell hibernate that it’s a large object and is not a simple
@Lob object
These are some annotations that are mostly used in order to work with hibernate.
72
4.6. NATIVE SQL :
You can use native SQL to express database queries if you want to utilize database-specific
features such as query hints or the CONNECT keyword in Oracle. Hibernate 3.x allows you to
specify handwritten SQL, including stored procedures, for all create, update, delete, and load
operations.
Your application will create a native SQL query from the session with
the createSQLQuery() method on the Session interface −
After you pass a string containing the SQL query to the createSQLQuery() method, you can
associate the SQL result with either an existing Hibernate entity, a join, or a scalar result using
addEntity(), addJoin(), and addScalar() methods respectively.
Scalar Queries
The most basic SQL query is to get a list of scalars (values) from one or more tables. Following
is the syntax for using native SQL for scalar values
[Link](Criteria.ALIAS_TO_ENTITY_MAP);
Entity Queries
The above queries were all about returning scalar values, basically returning the "raw" values
from the result set. Following is the syntax to get entity objects as a whole from a native sql
query via addEntity().
[Link]([Link]);
73
Named SQL Queries
Following is the syntax to get entity objects from a native sql query via addEntity() and using
named SQL query.
[Link]([Link]);
[Link]("employee_id", 10);
public Employee() {}
[Link] = fname;
[Link] = lname;
[Link] = salary;
return id;
74
public void setId( int id ) {
[Link] = id;
return firstName;
[Link] = first_name;
return lastName;
[Link] = last_name;
return salary;
[Link] = salary;
75
}}
);
"[Link]
<hibernate-mapping>
</meta>
<generator class="native"/>
</id>
76
<property name = "firstName" column = "first_name" type = "string"/>
</class>
</hibernate-mapping>
Finally, we will create our application class with the main() method to run the application where
we will use Native SQL queries −
import [Link].*;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
try {
77
throw new ExceptionInInitializerError(ex);
[Link]();
[Link]();
Transaction tx = null;
try {
tx = [Link]();
78
employeeID = (Integer) [Link](employee);
[Link]();
} catch (HibernateException e) {
if (tx!=null) [Link]();
[Link]();
} finally {
[Link]();
return employeeID;
Transaction tx = null;
try {
tx = [Link]();
[Link](Criteria.ALIAS_TO_ENTITY_MAP);
79
[Link](", Salary: " + [Link]("salary"));
[Link]();
} catch (HibernateException e) {
if (tx!=null) [Link]();
[Link]();
} finally {
[Link]();
Transaction tx = null;
try {
tx = [Link]();
[Link]([Link]);
80
[Link](" Salary: " + [Link]());
[Link]();
} catch (HibernateException e) {
if (tx!=null) [Link]();
[Link]();
} finally {
[Link]();
Here are the steps to compile and run the above mentioned application. Make sure, you have
set PATH and CLASSPATH appropriately before proceeding for the compilation and
execution.
• You would get the following result, and records would be created in the EMPLOYEE
table.
• $java ManageEmployee
81
• First Name: Daisy, Salary: 5000
• If you check your EMPLOYEE table, it should have the following records −
• +----+------------+-----------+--------+
• +----+------------+-----------+--------+
• +----+------------+-----------+--------+
• mysql>
4.7. SUMMARY:
This module brings about the various ways in which hibernate feature can be utilized in
[Link] architecture of hibernate is explained clearly and then the implementation of MVC is
explained. Then the several types of annotations are explained. The native SQL statements that
can be used with hibernate are also explained.
82
4.8. SELF-STUDY QUESTIONS:
[Link] the different native SQL statements that can be used with hibernate
83