Query Optimization   in Hibernate          by Singaram
HibernateA Hibernate application consists of 4 parts1. Hibernate Properties File2. Hibernate Mapping (XML) File3. Hibernat...
Database Schema
Message Class
Message Class (continued)
Hibernate Property File
Hibernate Mapping File
Initialization
Retrieving a Message
overviewRetrieving object from database is one of the most interesting andcomplex parts of working with hibernate. Hiberna...
Retrieving Object by IdentifierRetrieving by identifier:User user = (User) session.get(User.class, userID)It uses cache wh...
Hibernate Query Language HQL is an Object Oriented dialect of the familiar relational query  language SQL. It’s similar ...
Using Criteria Object• Once the desired criteria tree is built it’s executed against the  DB.• Query syntax is parsed and ...
QBE – Query by ExampleApplication supplies instance of the queried class with Criterionproperty value set, the Query then ...
Fetching Strategies Eager fetching or Join fetching – fetches data in a single  SELECT, using an OUTER JOIN . Immediate ...
Fetching CollectionsFor fetching collection lazy fetching is the best. <set name=”bids” lazy=”true” batch-size = “9”>  <ke...
Setting the fetch depthWe can set the maximum fetch depth globally. This settingcontrols the number of outer-joined tables...
The Query CacheQuery result sets may also be cached. This is only useful forqueries that are run frequently with the same ...
Tuning Object retrieval Enable the HQL log. Set hibernate,show_sql=true Step through your application use case by use ca...
Thank You!
Upcoming SlideShare
Loading in...5
×

Hibernate query optimization

3,843

Published on

0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
3,843
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
66
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Transcript of "Hibernate query optimization"

  1. 1. Query Optimization in Hibernate by Singaram
  2. 2. HibernateA Hibernate application consists of 4 parts1. Hibernate Properties File2. Hibernate Mapping (XML) File3. Hibernate Java Library4. HQL (Hibernate Query Language)and 1. Java Class Files 2. Database Schema
  3. 3. Database Schema
  4. 4. Message Class
  5. 5. Message Class (continued)
  6. 6. Hibernate Property File
  7. 7. Hibernate Mapping File
  8. 8. Initialization
  9. 9. Retrieving a Message
  10. 10. overviewRetrieving object from database is one of the most interesting andcomplex parts of working with hibernate. Hibernate provides thefollowing 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.
  11. 11. Retrieving Object by IdentifierRetrieving 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
  12. 12. 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();
  13. 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 
  14. 14. QBE – Query by ExampleApplication supplies instance of the queried class with Criterionproperty value set, the Query then returns all persistent instanceswith 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 ofproperty values to be matched by the returned resultsets.
  15. 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.
  16. 16. Fetching CollectionsFor 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
  17. 17. Setting the fetch depthWe 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 globallyEg:hibernate.max_fetch_depth=2Based on the fetch depth declared it will generate thequery with joins.
  18. 18. The Query CacheQuery result sets may also be cached. This is only useful forqueries that are run frequently with the same parameters.To use the query cache you must first enable it: hibernate.cache.use_query_cache=trueIt 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
  19. 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.
  20. 20. Thank You!
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×