0% found this document useful (0 votes)
94 views21 pages

Hibernate ntcc2k19

The document provides an overview of the Hibernate framework, including its architecture and main components. It discusses Hibernate's object-relational mapping capabilities and how it allows Java objects to be persisted to a database. The key aspects covered include: - Hibernate's architecture involves a configuration, session factory, session, queries to retrieve objects, first-level and second-level caches. - It provides object/relational mapping by allowing Java objects to be mapped to database tables. - Hibernate supports JPA and allows any Java class to be persisted following object-oriented principles. - Features like performance, scalability, and ease of maintenance are highlighted. - Examples
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
94 views21 pages

Hibernate ntcc2k19

The document provides an overview of the Hibernate framework, including its architecture and main components. It discusses Hibernate's object-relational mapping capabilities and how it allows Java objects to be persisted to a database. The key aspects covered include: - Hibernate's architecture involves a configuration, session factory, session, queries to retrieve objects, first-level and second-level caches. - It provides object/relational mapping by allowing Java objects to be mapped to database tables. - Hibernate supports JPA and allows any Java class to be persisted following object-oriented principles. - Features like performance, scalability, and ease of maintenance are highlighted. - Examples
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Hibernate Tutorial

Hibernate is an open source Java persistence framework project. It performs powerful object-
relational mapping and query databases using HQL and SQL. Hibernate is a great tool for ORM
mappings in Java. It can cut down a lot of complexity and thus defects as well from your
application, which may otherwise find a way to exist. This is specially boon for developers with
limited knowledge of SQL.

Initially started as an ORM framework, Hibernate has spun off into many projects, such as
Hibernate Search, Hibernate Validator, Hibernate OGM (for NoSQL databases), and so on.

Hibernate Architecture

The following diagram summarizes the main building blocks in hibernate architecture.

Hibernate Architecture

Let’s understand what each block represents.

1. Configuration : Generally written in hibernate.properties or hibernate.cfg.xml files. For


Java configuration, you may find class annotated with @Configuration. It is used by
Session Factory to work with Java Application and the Database. It represents an entire
set of mappings of an application Java Types to an SQL database.
2. Session Factory : Any user application requests Session Factory for a session object.
Session Factory uses configuration information from above listed files, to instantiates the
session object appropriately.
3. Session : This represents the interaction between the application and the database at any
point of time. This is represented by the org.hibernate.Session class. The instance of a
session can be retrieved from the SessionFactory bean.
4. Query : It allows applications to query the database for one or more stored objects.
Hibernate provides different techniques to query database, including NamedQuery and
Criteria API.
5. First-level cache : It represents the default cache used by Hibernate Session object while
interacting with the database. It is also called as session cache and caches objects within
the current session. All requests from the Session object to the database must pass
through the first-level cache or session cache. One must note that the first-level cache is
available with the session object until the Session object is live.
6. Transaction : enables you to achieve data consistency, and rollback incase something
goes unexpected.
7. Persistent objects : These are plain old Java objects (POJOs), which get persisted as one
of the rows in the related table in the database by hibernate.They can be configured in
configurations files (hibernate.cfg.xml or hibernate.properties) or annotated with @Entity
annotation.
8. Second-level cache : It is used to store objects across sessions. This needs to be explicitly
enabled and one would be required to provide the cache provider for a second-level
cache. One of the common second-level cache providers is EhCache.

Salient features of the Hibernate framework

 Object/Relational Mapping

Hibernate, as an ORM framework, allows the mapping of the Java domain object with
database tables and vice versa. As a result, business logic is able to access and manipulate
database entities via Java objects. It helps to speed up the overall development process by
taking care of aspects such as transaction management, automatic primary key
generation, managing database connections and related implementations, and so on.

 JPA provider

Hibernate does support the Java Persistence API (JPA) specification. JPA is a set of
specifications for accessing, persisting, and managing data between Java objects and
relational database entities.

 Idiomatic persistence

Any class that follows object-oriented principles such as inheritance, polymorphism, and
so on, can be used as a persistent class.

 High performance and scalability


Hibernate supports techniques such as different fetching strategies, lazy initialization,
optimistic locking, and so on, to achieve high performance, and it scales well in any
environment.

 Easy to maintain

Hibernate is easier to maintain as it requires no special database tables or fields. It


generates SQL at system initialization time. It is much quicker and easier to maintain
compared to JDBC.

In this page, I have categorized all available hibernate examples in this blog. This page will be
updated every time, a new hibernate tutorial is published in this blog. Stay Tuned !!

Feel free to suggest topics you want to read more on.

Hello world application

Hibernate 3 introduction and writing hello world application

In this post, I will try to detail out more information on hibernate and then will identify the basic
steps to use hibernate for our first running java hibernate example application.

Basic concepts

How to build SessionFactory in hibernate 4

If you have been watching previous hibernate releases then you must have noticed that they have
deprecated a lot of classes in quick succession. Deprecated classes are AnnotationConfiguration,
ServiceRegistryBuilder and so on.

In this hibernate tutorial, I am giving an example of building hibernate SessionFactory without


using deprecated classes mentioned above. I am using the latest hibernate version i.e. Hibernate
4.3.6.Final, so you can make sure that you are using the latest approach for building session
factory.

Entities Equality and Identity Concepts

Many times in our application, we face a situation where we have to compare two objects to
check their equality for satisfying some business rules. In core java, we have already much
knowledge about checking equality of objects, but in hibernate, we need to take care of a few
extra things as well. Let’s learn what are those extra concepts.

Defining Association Mappings between Hibernate Entities

When we annotate the java classes with JPA annotations and make them persistent entities, we
can face situations where two entities can be related and must be referenced from each other, in
either uni-direction or in bi-direction. Let’s understand a few basic things before actually
creating references between hibernate entities.

Entity / Persistence LifeCycle States Concepts

Given an instance of an object that is mapped to Hibernate, it can be in any one of four different
states: transient, persistent, detached, or removed. We are going to learn about them today in this
hibernate tutorial.

Using In-memory Database With Hibernate

In this example, I am using HSQLDB Database for creating and accessing in-memory database
through our hibernate code.

Hibernate JPA Cascade Types

To enable cascade and inverse effect, we had used “CascadeType” attribute in entities. In this
tutorial, we will learn about various type of available options for cascading via CascadeType.

Pros and Cons of Hibernate Annotations Vs Mappings

As you may know that prior to the inline annotations, the only way to create hibernate mappings
was through XML files. Although various tools from Hibernate and third-party projects allowed
part or all of these mappings to be generated from Java source code automatically. Today
annotations are the newest way to define mappings but it is not automatically the best way to do
so. Let’s discuss the drawbacks and benefits of hibernate (or I should say JPA) annotations
before discussing when to apply them.

Hibernate Query Language [HQL]

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. It is a superset of the JPQL, the
Java Persistence Query Language; a JPQL query is a valid HQL query, but not all HQL queries
are valid JPQL queries. HQL is a language with its own syntax and grammar.

Let’s learn HQL using the following examples:

1. Basic HQL Syntax


o Update Operation
o Delete Operation
o Insert Operation
o Select Operation
2. The from Clause and Aliases
3. The select Clause and Projection
4. Using Named Parameters
5. Paging Through the Result Set
6. Obtaining a Unique Result
7. Sorting Results with the order by Clause
8. Associations
9. Aggregate Methods
10. Named Queries
11. Using Native SQL
12. Enable Logging and Commenting

Hibernate Criteria Queries

The Criteria Query API lets you build nested, structured query expressions in Java, providing a
compile-time syntax checking that is not possible with a query language like HQL or SQL. The
Criteria API also includes query by example (QBE) functionality. This lets you supply example
objects that contain the properties you would like to retrieve instead of having to step-by-step
spell out the components of the query. It also includes projection and aggregation methods,
including count(). Let’s explore it’s different features in detail.

1. Basic Usage Example


2. Using Restrictions with Criteria
3. Paging Through the Result Set
4. Obtaining a Unique Result
5. Obtaining Distinct Results
6. Sorting the Query’s Results
7. Performing Associations (Joins)
8. Adding Projections
9. Query By Example (QBE)
10. Summary

Lazy Loading in Hibernate

In this this tutorial, I will be discussing a must-known feature in hibernate known as lazy
loading. This is useful specially if you working in a very large application.

CRUD Operation Examples

Hello world insert data

In this tutorial, I am giving example of inserting data in a single table.

Hibernate named query tutorial

Named queries in hibernate is a technique to group the HQL statements in single location, and
lately refer them by some name whenever need to use them. It helps largely in code cleanup
because these HQL statements are no longer scattered in whole code.

Loading entity from database example


Examples of loading an hibernate entity using either load or get method.

Save() and saveOrUpdate() for Saving Entities

Please not that creating an instance of a class, you mapped with a hibernate annotations, does not
automatically persist the object to the database. It must be save explicitly after attaching it to a
valid hibernate session. Let’s learn how to do it.

Merging and Refreshing Entities

In this tutorial, I am discussing few thoughts around refresh() and merge() method present in
hibernate session class.

Hibernate entity mappings

Hibernate one to one mapping using annotations

Let’s discuss variations of one-to-one mappings supported in hibernate:

1. Using foreign key association


2. Using a common join table
3. Using shared primary key

Hibernate one to many mapping using annotations

Discuss variations of one-to-many mappings supported in hibernate:

1. Using foreign key association


2. Using a join table

Hibernate many to many mapping using annotations

Discuss variations of many-to-many mappings supported in hibernate.

Hibernate Connection Pooling and Caching

C3P0 Connection Pool Configuration Tutorial

By default, Hibernate uses JDBC connections in order to interact with a database. Creating these
connections is expensive—probably the most expensive single operation Hibernate will execute
in a typical-use case. Since JDBC connection management is so expensive that possibly you will
advise to use a pool of connections, which can open connections ahead of time (and close them
only when needed, as opposed to “when they’re no longer used”).

C3P0 is an example of an external connection pool. In this tutorial, we will learn to use it with
hibernate.
Hibernate EhCache configuration

Caching is facility provided by ORM frameworks which help users to get fast running web
application, while help framework itself to reduce the number of queries made to the database in
a single transaction. Hibernate also provide this caching functionality at first level and second
level.

In this tutorial, I am giving an example using ehcache configuration as second level cache in
hibernate.

Hibernate first level cache with example

Fist level cache in hibernate is enabled by default and you do not need to do anything to get this
functionality working. Let’s learn more about it.

Hibernate second level cache with example

In this tutorial, I am giving concepts around hibernate second level cache and give example using
code snippets.

Hibernate best practices

Hibernate @NaturalId usage and example

Hibernate 4 has bring lots of improvements and @NaturalId is one of such nice improvements.
As you know @Id annotation is used as meta data for specifying the primary key of an entity.
But sometimes, entity is usually used in DAO layer code with id which not not primary key but
its logical or natural id. In such cases, @NaturalId annotation will prove good replacement of
named queries in hibernate.

Get entity reference for lazy loading

Lazy loading is a design pattern commonly used in computer programming to defer initialization
of an object until the point at which it is needed. Hibernate lazy loading can be done by
specifying “fetch= FetchType.LAZY” in hibernate mapping annotations.

Integration with other frameworks

Integrate Hibernate with Spring framework

This hibernate tutorial is focused on usage of Hibernate with Spring 3 framework. I will show
that how a basic end to end application flow looks like as a result of this integration.

First Hibernate Example without IDE


Here, we are going to create the first hibernate application without IDE. For creating the first
hibernate application, we need to follow the following steps:

1. Create the Persistent class


2. Create the mapping file for Persistent class
3. Create the Configuration file
4. Create the class that retrieves or stores the persistent object
5. Load the jar file
6. Run the first hibernate application by using command prompt

1) Create the Persistent class

A simple Persistent class should follow some rules:

 A no-arg constructor: It is recommended that you have a default constructor at least


package visibility so that hibernate can create the instance of the Persistent class by
newInstance() method.
 Provide an identifier property: It is better to assign an attribute as id. This attribute
behaves as a primary key in database.
 Declare getter and setter methods: The Hibernate recognizes the method by getter and
setter method names by default.
 Prefer non-final class: Hibernate uses the concept of proxies, that depends on the
persistent class. The application programmer will not be able to use proxies for lazy
association fetching.

Let's create the simple Persistent class:

Employee.java

1. package com.javatpoint.mypackage;  
2.   
3. public class Employee {  
4. private int id;  
5. private String firstName,lastName;  
6.   
7. public int getId() {  
8.     return id;  
9. }  
10. public void setId(int id) {  
11.     this.id = id;  
12. }  
13. public String getFirstName() {  
14.     return firstName;  
15. }  
16. public void setFirstName(String firstName) {  
17.     this.firstName = firstName;  
18. }  
19. public String getLastName() {  
20.     return lastName;  
21. }  
22. public void setLastName(String lastName) {  
23.     this.lastName = lastName;  
24. }  
25.   
26.   
27. }  

2) Create the mapping file for Persistent class

The mapping file name conventionally, should be class_name.hbm.xml. There are many
elements of the mapping file.

 hibernate-mapping : It is the root element in the mapping file that contains all the
mapping elements.
 class : It is the sub-element of the hibernate-mapping element. It specifies the Persistent
class.
 id : It is the subelement of class. It specifies the primary key attribute in the class.
 generator : It is the sub-element of id. It is used to generate the primary key. There are
many generator classes such as assigned, increment, hilo, sequence, native etc. We will
learn all the generator classes later.
 property : It is the sub-element of class that specifies the property name of the Persistent
class.

Let's see the mapping file for the Employee class:

employee.hbm.xml

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-mapping PUBLIC  
3.  "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
4.  "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">  
5.   
6.  <hibernate-mapping>  
7.   <class name="com.javatpoint.mypackage.Employee" table="emp1000">  
8.     <id name="id">  
9.      <generator class="assigned"></generator>  
10.     </id>  
11.             
12.     <property name="firstName"></property>  
13.     <property name="lastName"></property>  
14.             
15.   </class>  
16.             
17.  </hibernate-mapping>  

3) Create the Configuration file

The configuration file contains information about the database and mapping file. Conventionally,
its name should be hibernate.cfg.xml .

hibernate.cfg.xml

1. <?xml version='1.0' encoding='UTF-8'?>  
2. <!DOCTYPE hibernate-configuration PUBLIC  
3.           "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
4.           "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">  
5.   
6. <hibernate-configuration>  
7.   
8.     <session-factory>  
9.         <property name="hbm2ddl.auto">update</property>  
10.         <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>  
11.         <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>  
12.         <property name="connection.username">system</property>  
13.         <property name="connection.password">jtp</property>  
14.         <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</proper
ty>  
15.     <mapping resource="employee.hbm.xml"/>  
16.     </session-factory>  
17.   
18. </hibernate-configuration>  

4) Create the class that retrieves or stores the object

In this class, we are simply storing the employee object to the database.

1. package com.javatpoint.mypackage;    
2.     
3. import org.hibernate.Session;    
4. import org.hibernate.SessionFactory;    
5. import org.hibernate.Transaction;  
6. import org.hibernate.boot.Metadata;  
7. import org.hibernate.boot.MetadataSources;  
8. import org.hibernate.boot.registry.StandardServiceRegistry;  
9. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
10.   
11.     
12. public class StoreData {    
13. public static void main(String[] args) {    
14.         
15.     //Create typesafe ServiceRegistry object    
16.     StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hiber
nate.cfg.xml").build();  
17.           
18.    Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();  
19.   
20. SessionFactory factory = meta.getSessionFactoryBuilder().build();  
21. Session session = factory.openSession();  
22. Transaction t = session.beginTransaction();   
23.             
24.     Employee e1=new Employee();    
25.     e1.setId(101);    
26.     e1.setFirstName("Gaurav");    
27.     e1.setLastName("Chawla");    
28.         
29.     session.save(e1);  
30.     t.commit();  
31.     System.out.println("successfully saved");    
32.     factory.close();  
33.     session.close();    
34.         
35. }    
36. }   

5) Load the jar file

For successfully running the hibernate application, you should have the hibernate5.jar file.

Download the required jar files for hibernate

6) How to run the first hibernate application without IDE

We may run this hibernate application by IDE (e.g. Eclipse, Myeclipse, Netbeans etc.) or without
IDE. We will learn about creating hibernate application in Eclipse IDE in next chapter.
To run the hibernate application without IDE:

 Install the oracle10g for this example.


 Load the jar files for hibernate. (One of the way to load the jar file is copy all the jar files
under the JRE/lib/ext folder). It is better to put these jar files inside the public and private
JRE both.
 Now, run the StoreData class by java com.javatpoint.mypackage.StoreData

Hibernate Logging by Log4j using xml file

Logging enables the programmer to write the log details into a file permanently. Log4j and
Logback frameworks can be used in hibernate framework to support logging.

There are two ways to perform logging using log4j:

1. By log4j.xml file (or)


2. By log4j.properties file

Levels of Logging

Following are the common logging levels.

Levels Description

OFF This level is used to turn off logging.

WARNING This is a message level that indicates a problem.

SEVERE This is a message level that indicates a failure.


INFO This level is used for informational messages.

CONFIG This level is used for static configuration messages.

Steps to perform Hibernate Logging by Log4j using xml file

There are two ways to perform logging using log4j using xml file:

1. Load the log4j jar files with hibernate


2. Create the log4j.xml file inside the src folder (parallel with hibernate.cfg.xml file)

Example of Hibernate Logging by Log4j using xml file

You can enable logging in hibernate by following only two steps in any hibernate example. This
is the first example of hibernate application with logging support using log4j.

Load the required jar files

You need to load the slf4j.jar and log4j.jar files with hibernate jar files.

download all the required jar files

Create log4j.xml file

Now you need to create log4j.xml file. In this example, all the log details will be written in the
C:/javatpointlog.log file.

log4j.xml

1. <?xml version="1.0" encoding="UTF-8"?>  
2. <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">  
3. <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"  
4.     debug="false">  
5. <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">  
6.  <layout class="org.apache.log4j.PatternLayout">  
7.   <param name="ConversionPattern" value="[%d{dd/MM/yy hh:mm:ss:sss z}] %5p %c{
2}: %m%n" />  
8.  </layout>  
9. </appender>  
10.     <appender name="ASYNC" class="org.apache.log4j.AsyncAppender">  
11.         <appender-ref ref="CONSOLE" />  
12.         <appender-ref ref="FILE" />  
13. </appender>  
14. <appender name="FILE" class="org.apache.log4j.RollingFileAppender">  
15.     <param name="File" value="C:/javatpointlog.log" />  
16.     <param name="MaxBackupIndex" value="100" />  
17.  <layout class="org.apache.log4j.PatternLayout">  
18.   <param name="ConversionPattern" value="[%d{dd/MM/yy hh:mm:ss:sss z}] %5p %c{
2}: %m%n" />  
19. </layout>  
20. </appender>  
21.     <category name="org.hibernate">  
22.         <priority value="DEBUG" />  
23.     </category>  
24.     <category name="java.sql">  
25.         <priority value="debug" />  
26.     </category>  
27.     <root>  
28.         <priority value="INFO" />  
29.         <appender-ref ref="FILE" />  
30.     </root>  
31. </log4j:configuration>  

Collection Mapping in Hibernate

We can map collection elements of Persistent class in Hibernate. You need to declare the type of
collection in Persistent class from one of the following types:

 java.util.List
 java.util.Set
 java.util.SortedSet
 java.util.Map
 java.util.SortedMap
 java.util.Collection
 or write the implementation of org.hibernate.usertype.UserCollectionType

Mapping collection in mapping file

There are many subelements of <class> elements to map the collection. They are <list>, <bag>,
<set> and <map>. Let's see how we implement the list for the above class:

1. <class name="com.javatpoint.Question" table="q100">  
2.           <id name="id">  
3.           <generator class="increment"></generator>  
4.           </id>  
5.           <property name="qname"></property>  
6.           <list name="answers" table="ans100">  
7.           <key column="qid"></key>  
8.           <index column="type"></index>  
9.           <element column="answer" type="string"></element>  
10.           </list>  
11.             
12.           </class>  

There are three subelements used in the list:

 <key> element is used to define the foreign key in this table based on the Question class
identifier.
 <index> element is used to identify the type. List and Map are indexed collection.
 <element> is used to define the element of the collection.

This is the mapping of collection if collection stores string objects. But if collection stores entity
reference (another class objects), we need to define <one-to-many> or <many-to-many>
element. Now the Persistent class will look like:

1. package com.javatpoint;  
2.   
3. import java.util.List;  
4.   
5. public class Question {  
6. private int id;  
7. private String qname;  
8. private List<Answer> answers;//Here, List stores the objects of Answer class  
9.   
10. //getters and setters  
11.   
12. }  

1. package com.javatpoint;  
2. import java.util.List;  
3. public class Answer {  
4. private int id;  
5. private String answer;  
6. private String posterName;  
7. //getters and setters  
8. }  

Now the mapping file will be:

1. <class name="com.javatpoint.Question" table="q100">  
2.           <id name="id">  
3.           <generator class="increment"></generator>  
4.           </id>  
5.           <property name="qname"></property>  
6.             
7.           <list name="answers" >  
8.           <key column="qid"></key>  
9.           <index column="type"></index>  
10.           <one-to-many class="com.javatpoint.Answer" />  
11.           </list>  
12.             
13.           </class>  

Here, List is mapped by one-to-many relation. In this scenario, there can be many answers for
one question.

Understanding key element

The key element is used to define the foreign key in the joined table based on the original
identity. The foreign key element is nullable by default. So for non-nullable foreign key, we need
to specify not-null attribute such as:

1. <key column="qid" not-null="true" ></key>  

The attributes of the key element are column, on-delete, property-ref, not-null, update and
unique.

1. <key  
2. column="columnname"  
3. on-delete="noaction|cascade"  
4. not-null="true|false"  
5. property-ref="propertyName"  
6. update="true|false"  
7. unique="true|false"  
8. />  

Indexed collections

The collection elements can be categorized in two forms:

 indexed ,and
 non-indexed
The List and Map collection are indexed whereas set and bag collections are non-indexed. Here,
indexed collection means List and Map requires an additional element <index>.

Collection Elements

The collection elements can have value or entity reference (another class object). We can use one
of the 4 elements

 element
 component-element
 one-to-many, or
 many-to-many

The element and component-element are used for normal value such as string, int etc. whereas
one-to-many and many-to-many are used to map entity reference.

Upcoming topics in Collection Mapping


Mapping List

In this example, we are going to map the List element.

Mapping Bag

In this example, we are going to use the bag collection of Hibernate framework.

Mapping Set

Here, we will map the set element of collection.

Hibernate Transaction Management Example

A transaction simply represents a unit of work. In such case, if one step fails, the whole
transaction fails (which is termed as atomicity). A transaction can be described by ACID
properties (Atomicity, Consistency, Isolation and Durability).
Transaction Interface in Hibernate

In hibernate framework, we have Transaction interface that defines the unit of work. It
maintains abstraction from the transaction implementation (JTA,JDBC).

A transaction is associated with Session and instantiated by calling session.beginTransaction().

The methods of Transaction interface are as follows:

1. void begin() starts a new transaction.


2. void commit() ends the unit of work unless we are in FlushMode.NEVER.
3. void rollback() forces this transaction to rollback.
4. void setTimeout(int seconds) it sets a transaction timeout for any transaction started by
a subsequent call to begin on this instance.
5. boolean isAlive() checks if the transaction is still alive.
6. void registerSynchronization(Synchronization s) registers a user synchronization
callback for this transaction.
7. boolean wasCommited() checks if the transaction is commited successfully.
8. boolean wasRolledBack() checks if the transaction is rolledback successfully.
Example of Transaction Management in Hibernate

In hibernate, it is better to rollback the transaction if any exception occurs, so that resources can
be free. Let's see the example of transaction management in hibernate.

1. Session session = null;  
2. Transaction tx = null;  
3.   
4. try {  
5. session = sessionFactory.openSession();  
6. tx = session.beginTransaction();  
7. //some action  
8.   
9. tx.commit();  
10.   
11. }catch (Exception ex) {  
12. ex.printStackTrace();  
13. tx.rollback();  
14. }  
15. finally {session.close();}  

Hibernate Query Language (HQL)

Hibernate Query Language (HQL) is same as SQL (Structured Query Language) but it doesn't
depends on the table of the database. Instead of table name, we use class name in HQL. So it is
database independent query language.

Advantage of HQL

There are many advantages of HQL. They are as follows:

 database independent
 supports polymorphic queries
 easy to learn for Java Programmer
Query Interface

It is an object oriented representation of Hibernate Query. The object of Query can be obtained
by calling the createQuery() method Session interface.

The query interface provides many methods. There is given commonly used methods:

1. public int executeUpdate() is used to execute the update or delete query.


2. public List list() returns the result of the ralation as a list.
3. public Query setFirstResult(int rowno) specifies the row number from where record
will be retrieved.
4. public Query setMaxResult(int rowno) specifies the no. of records to be retrieved from
the relation (table).
5. public Query setParameter(int position, Object value) it sets the value to the JDBC
style query parameter.
6. public Query setParameter(String name, Object value) it sets the value to a named
query parameter.

Example of HQL to get all the records

1. Query query=session.createQuery("from Emp");//here persistent class name is Emp  
2. List list=query.list();  

Example of HQL to get records with pagination

1. Query query=session.createQuery("from Emp");  
2. query.setFirstResult(5);  
3. query.setMaxResult(10);  
4. List list=query.list();//will return the records from 5 to 10th number  

Example of HQL update query

1. Transaction tx=session.beginTransaction();  
2. Query q=session.createQuery("update User set name=:n where id=:i");  
3. q.setParameter("n","Udit Kumar");  
4. q.setParameter("i",111);  
5.   
6. int status=q.executeUpdate();  
7. System.out.println(status);  
8. tx.commit();  
Example of HQL delete query

1. Query query=session.createQuery("delete from Emp where id=100");  
2. //specifying class name (Emp) not tablename  
3. query.executeUpdate();  

HQL with Aggregate functions

You may call avg(), min(), max() etc. aggregate functions by HQL. Let's see some common
examples:

Example to get total salary of all the employees

1. Query q=session.createQuery("select sum(salary) from Emp");  
2. List<Integer> list=q.list();  
3. System.out.println(list.get(0));  

Example to get maximum salary of employee

1. Query q=session.createQuery("select max(salary) from Emp");  

Example to get minimum salary of employee

1. Query q=session.createQuery("select min(salary) from Emp");  

Example to count total number of employee ID

1. Query q=session.createQuery("select count(id) from Emp");  

Example to get average salary of each employees

1. Query q=session.createQuery("select avg(salary) from Emp");  

You might also like