You are on page 1of 20

Query Optimization

in Hibernate
by Singaram
Hibernate

A Hibernate application consists of 4 parts

1. Hibernate Properties File


2. Hibernate Mapping (XML) File
3. Hibernate Java Library
4. HQL (Hibernate Query Language)

and

1. Java Class Files


2. Database Schema
2
Database Schema

3
Message Class

4
Message Class (continued)

5
Hibernate Property File

6
Hibernate Mapping File

7
Initialization

8
Retrieving a Message

9
overview
Retrieving object from database is one of the most interesting and
complex parts of working with hibernate. Hibernate provides the
following ways for getting objects out of the database: 
 
 Retrieving by identifier. 

 Using Hibernate Query Language (HQL) which is a fully Object


oriented query language.
 
 Using Hibernate Criteria API – Provides a Type safe and OO
way to perform queries without String manipulation
 
 Using Native SQL query Hibernate takes care of mapping the
resultsets.

10
Retrieving Object by Identifier
Retrieving by identifier:

User user = (User) session.get(User.class, userID)


It uses cache when it is already loaded Get() method returns null
When it cannot find the object in cache or Database.

User user = (User) session.load(User.class, userID)


If Load() can’t find the Object then it throws an Exception.
 

Retrieving object by identifier isn’t a flexible way as using


arbitrary queries

11
Hibernate Query Language

 HQL is an Object Oriented dialect of the familiar relational query


language SQL.
 It’s similar to OQL and EJB-QL.
 It’s not a DML like SQL.
 It’s used only for object retrieval
 
Query q = session.CreateQuery
(“from User u where u.firstName = :fname”);
q.getString(“fname”,”Ram”);
List result = q.list();

12
Using Criteria Object
• Once the desired criteria tree is built it’s executed against the DB.

• Query syntax is parsed and validated at compile time

• Good aspect about Hibernate Criteria API is the Criterion


framework which can be extended by the user.

Criteria criteria = session.createCriteria(User.class);


Criteria.add( Expression.like(“firstname”. “Ram”));
List result = criteria.list();

Criteria  tree of criterion instances


Expression  static factory methods that return Criterion instances
 

13
QBE – Query by Example
Application supplies instance of the queried class with Criterion
property value set, the Query then returns all persistent instances
with matching property values.

User exampleUser = new User();


exampleUser.setName(“SAM”);

Criteria criteria = session.createCriteria(User.class);


Criteria.add( Example.create(exampleUser));
List result = criteria.list();

Typical use is a search screen that allows user to specify a range of


property values to be matched by the returned resultsets.

14
Fetching Strategies

 Eager fetching or Join fetching – fetches data in a single


SELECT, using an OUTER JOIN .

 Immediate fetching – The associated object is fetched


immediately, using a sequential database read.

  Lazy or Select fetching –second SELECT is used to fetch the


data. Unless you explicitly disable lazy fetching by specifying
lazy="false", this second select will only be executed when you
actually access the association.

 Batch fetching - an optimization strategy for select fetching,


fetching a batch of objects or collections.
15
Fetching Collections

For fetching collection lazy fetching is the best.


 
<set name=”bids” lazy=”true” batch-size = “9”>
<key column=”ITEM_ID”/>
<one-to-many class= “BID”/>
</set>

 Outer-Join – true  eager fetching


 Lazy=”true”  lazily fetches the collection.
 Neither attribute specified  fetched from 2nd level cache or
immediate extra SQL query

16
Setting the fetch depth
We can set the maximum fetch depth globally. This setting
controls the number of outer-joined tables that hibernate will
use in a single query.

For this we have to configure in hibernate.cfg.xml globally


Eg:
hibernate.max_fetch_depth=2

Based on the fetch depth declared it will generate the


query with joins.

17
The Query Cache

Query result sets may also be cached. This is only useful for
queries that are run frequently with the same parameters.
To use the query cache you must first enable it:

hibernate.cache.use_query_cache=true

It creates Two new cache regions


 org.hibernate.cache.StandardQueryCache  holding cached
query result sets
 UpdateTimestampsCache  holding timestamps of the most
recent updates to queryable tables

18
Tuning Object retrieval

 Enable the HQL log. Set hibernate,show_sql=true

 Step through your application use case by use case and


note how many and what SQL statements Hibernate
executes

 If join operation are too complex and slow set outer join to
false for <many-to-one>

 If too many SQL statements are executed use


Lazy=”false” for all collection mapping.

19
Thank You!

You might also like