hibernate query optimization

20
Query Optimization in Hibernate by Singaram

Upload: kamalakar-dandu

Post on 15-May-2015

3.549 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Hibernate query optimization

Query Optimizationin Hibernate

by Singaram

Page 2: Hibernate query optimization

2

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

Page 3: Hibernate query optimization

3

Database Schema

Page 4: Hibernate query optimization

4

Message Class

Page 5: Hibernate query optimization

5

Message Class (continued)

Page 6: Hibernate query optimization

6

Hibernate Property File

Page 7: Hibernate query optimization

7

Hibernate Mapping File

Page 8: Hibernate query optimization

8

Initialization

Page 9: Hibernate query optimization

9

Retrieving a Message

Page 10: Hibernate query optimization

10

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.

Page 11: Hibernate query optimization

11

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 nullWhen 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

Page 12: Hibernate query optimization

12

Hibernate Query Language

HQL is an Object Oriented dialect of the familiar relational querylanguage 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();

Page 13: Hibernate query optimization

13

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 instancesExpression static factory methods that return Criterion instances

 

Page 14: Hibernate query optimization

14

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.

Page 15: Hibernate query optimization

15

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.

Page 16: Hibernate query optimization

16

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

Page 17: Hibernate query optimization

17

Setting the fetch depth

We can set the maximum fetch depth globally. This settingcontrols the number of outer-joined tables that hibernate

willuse 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 thequery with joins.

Page 18: Hibernate query optimization

18

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

Page 19: Hibernate query optimization

19

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.

Page 20: Hibernate query optimization

Thank You!