Performance Zone is brought to you in partnership with:

Ming has posted 1 posts at DZone. View Full User Profile

Hibernate Performance Tuning

06.10.2009
| 85624 views |
  • submit to reddit

Hibernate is a powerful, high performance object/relational persistence and query service. Hibernate lets you develop persistent classes following object-oriented idiom - including association, inheritance, polymorphism, composition, and collections. Hibernate allows you to express queries in its own portable SQL extension (HQL), as well as in native SQL, or with an object-oriented Criteria and Example API.

Quintessential to using any ORM framework like hibernate is to know how to leverage the various performance tuning methods supported by the framework.

In this volume Wings Jiang discusses three performance tuning strategies for hibernate:

  1. SQL Optimization
  2. Session Management
  3. Data Caching

 

SQL Optimization

When using Hibernate in your application, you already have been coding HQL (Hibernate Query Language) somewhere. For example, “from User user where user.name = ‘John’”. If issuing your SQL statement like this, Hibernate cannot use the SQL cache implemented by database because name of the user, in most scenarios, is extremely distinct. On the contrary, while using placeholder to achieve this, like “from User user where user.name =?” will be cached by the Database to fulfill the performance improvement. You can also set some Hibernate properties to improve performance, such as setting the number of records retrieved while fetching records via configuring property hibernate.jdbc.fetch_size, setting the batch size when committing the batch processing via configuring property hibernate.jdbc.batch_size and switching off the SQL output via setting property hibernate.show_sql to false in product environments. In addition, the performance tuning of your target Database is also significant, like SQL clauses tuning, reasonable indexes, delicate table structures, data partitions etc.

Session Management

Undoubtedly, Session is the pith of Hibernate. It manages the Database related attributes, such as JDBC connections, data entities’ states. Managing the Session efficiently is the key to getting high performance in enterprise applications. One of the many commonly used and equally elegant approaches to session management in hibernate is to use ThreadLocal. Threadlocal will create a local copy of session for every thread. Thus synchronization problems are averted, when objects are put in the Threadlocal, . To understand how ThreadLocal variables are used in Java, refer to Sun Java Documentation at http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ThreadLocal.html

Data Caching

Before accomplishing any data caching, it is essential to set the property hibernate.cache.user_query_cache = true.
There are three kinds of commonly used Caching Strategies in Hibernate:
Using cache based on Session level (aka Transaction layer level cache). This is also called first-level cache.

Using cache based on SessionFactory level (Application layer level cache). This is also called second-level cache.

Using cluster cache which is employed in distributed application (in different JVMs). In fact, some techniques, like loading data by id, lazy initialization which betokens loading appropriate data in proper time rather than obtaining a titanic number of  useless records, which are fairly useless in the subsequent operations are consummated via data caching.

First Level Cache (aka Transaction layer level cache)

Fetching an object from database always has a cost associated with it. This can be offset by storing the entities in hibernate session. Next time the entities are required, they are fetched from the session, rather than fetching from the database.

To clear an object from the session use: session.evict(object). To clear all the objects from the session use session.clear().

Second Level Cache (aka Application layer level cache)

 

In this approach, if an object is not found in session, it is searched for in the session factory before querying the database for the object.
If an object is indeed fetched from database, the selected data should be put in session cache. This would improve the performance when the object is required next time. To remove an entity from session factory use the various overloaded implementations of evict() method of SessionFactory.

In fact, Hibernate lets you tailor your own caching implementation by specifying the name of a class that implements org.hibernate.cache.CacheProvider using the property hibernate.cache.provider_class. But it is recommended to employ a few built-in integrations with open source cache providers (listed below).

Cache

Type

Cluster Safe

Query Cache Supported

Hashtable

Memory

 NO

YES

EHCache

Memory, Disk

 NO

YES

OSCache

Memory, Disk

 NO

YES

SwarmCache

Clustered

YES (clustered invalidation)

 NO

JBoss TreeCache

Clustered

YES (replication)

YES

Terracota

Clustered

YES

YES

 

In order to use second level caching, developers have to append some configurations in hibernate.cfg.xml (for example, using EHCache here).

<hibernate-configuration>
<session-factory>
<property name="hibernate.cache.provider_class">
net.sf.ehcache.hibernate.Provider
</property>
</session-factory>
</hibernate-configuration>

In addition, developers also need to create a cache specific configuration file (Example: ehcache.xml for EHCache).

<ehcache>
<diskStore path="java.io.tmpdir"/> (1)
<defaultCache
maxElementsInMemory="10000" (2)
eternal="false" (3)
timeToIdleSeconds="120" (4)
timeToLiveSeconds="120" (5)
overflowToDisk="true" (6)
/>
</ehcache>
  1. diskStore : Sets the path to the directory where cache .data files are created. The following properties are translated:
    a.user.home - User's home directory
    b.user.dir - User's current working directory
    c.java.io.tmpdir (Default temp file path)
  2. maxElementsInMemory : Sets the maximum number of objects that will be created in memory.
  3. eternal : Sets whether elements are eternal. If eternal,  timeouts are ignored and the element is never expired.
  4. timeToIdleSeconds : Sets the time to idle for an element before it expires. Is only used if the element is not eternal. Idle time is now - last accessed time.
  5. timeToLiveSeconds : Sets the time to live for an element before it expires. Is only used if the element is not eternal. TTL is now - creation time
  6. overflowToDisk : Sets whether elements can overflow to disk when the in-memory cache has reached the maxInMemory limit.

Finally the cache concurrency strategy has to be specified in mapping files. For example, the following code fragment shows how to configure your cache strategy.

<class name="org.jmatrix.user.User" table="USER">
<cache usage=”read-write” />

<set name="address" … >
<cache usage="read-only" />
</set>

</class>
Legacy
Published at DZone with permission of its author, Ming Jiang.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Andreas Grabner replied on Wed, 2009/06/10 - 5:47pm

Getting insight into frameworks like Hibernate is essential to correctly implement solutions on top of those frameworks. Alois Reitbauer - Technology Strategist from dynaTrace - wrote 3 great articles dedicated to the internals of Hibernate Caches - its worth reading them as they give insight into the internals of the cahces:
  • Understanding Caching in Hibernate - Part One : The Session Cache
  • Understanding Caching in Hibernate - Part Two : The Query Cache
  • Understanding Caching in Hibernate - Part Three : The Second Level Cache

    Andi
  • Ming Jiang replied on Thu, 2009/06/11 - 1:28am

    Hibernate is quite popular in current IT world.

    Ayo Bakare replied on Thu, 2009/07/30 - 7:01pm

    I have to agree,I use it all the time Free Macbook | Free iPhone 3GS

    Chris Jones replied on Wed, 2009/10/07 - 3:53pm

    Great artilce but it really annoys me how the whole Hibernate stacks are not versioned consistently? Surely Hibernate Core 3.4.0 release should bounce all sister projects to version 3.4.0, do you not think? It would be the best ensurance of compatibility. In the meantime, point releases 3.4.x of individual projects could be developed independently.

    Chris Jones, London, UK
    My Projects:
    Free Slim PS3 | Free Gadgets

    Jason Adams replied on Wed, 2009/10/21 - 3:19am

    I love hibernate. We use it quite a lot.

    e cigarette | e cigarettes

    kalle pallo replied on Tue, 2009/10/27 - 1:46pm

    Hibernate also provides data query and retrieval facilities. Hibernate generates the SQL calls and relieves the developer from manual result set handling and object conversion, keeping the application portable to all supported SQL databases, with database portability delivered at very little performance overhead. piilolinssit ja ongelmatilanteet

    Nia Broad replied on Tue, 2009/11/10 - 11:28pm

    Nice article. I agree with what you said. Thanks

    Katie Love replied on Sun, 2010/11/07 - 5:47am

    I think youve made some truly interesting points. Not too many people would actually think about this the way you just did. Im really impressed that theres so much about this subject thats been uncovered and you did it so well, with so much class. Good one you, man! Really great stuff here. Free Laptops | Free iPhone

     

    Arno Huetter replied on Thu, 2011/01/27 - 4:33am

    Nice article, although I resort to second-level caching only when there are no other options left. In my experience, many performance problems simply stem from loading too many mapped objects into the session. E.g. by trying to eager-load several to-many associations within the same query, what you actually get are join-duplicates, hence duplicate mapped object instantiations (AKA cartesian product). Some counter-measures are explained in this article.

    Jordan Garden replied on Wed, 2011/06/01 - 6:29am

    I like this article as its very well written and precise, performance tuning has always confused me in the past and have been looking for some good articles to explain to me in a simple way, this article has done just that Orchid Care

    Paul Archer replied on Thu, 2011/10/20 - 4:33am

    This is a helpful article on hibernate performance tuning. Since Hibernate is so useful and gaining popularity, such an article would help newcomers optimise their usage experience.

    Comment viewing options

    Select your preferred way to display the comments and click "Save settings" to activate your changes.