Powered by Blogger.

Hibernate Caching Techniques

>> Wednesday, May 18, 2011

Caching is a Temporary memory or buffer which resides at client side and stores the results sent by server. When client generates same request for multiple number of times, the first request generated results will be stored in cache and this result will be used across the multiple requests. This reduces the round trips between the client and server. Since the result will be collected from cache that is available at client side.
Hibernate supports for 2 levels of cache:
  1. Level one cache
  2. Level two cache.

Level One Cache:
Level 1 cache is inbuilt cache and it will be associated with hibernate session objects. Every session object of hibernate application contains one inbuilt level one cache.

Responsibilities of Level one cache:
a)      If select query executed for multiple no of times with in a session. Only one time query goes to database software gets the result, remaining all the times result will be gathered from cache.
b)      If one of pojo class object is modified for multiple no of times with in a transaction of session object, instead of sending update query for multiple number of times, all the changes done on the object wil be kept tracked and only one update query wil be generated reflecting all the changes at the end of the transaction.
The different ways to remove the level 1 cache from session

i)  Session.flush( ) –>  Flushes level one cache content to db software
ii)  Session.evict( ) –> Remove the content of level 1 cache
iii) Session.close( ) –> closes level 1 cache, before that it calls session.flush()

A hibernate client application can have multiple level1 caches because a hibernate application can have multiple hibernate session objects.
The data stored in level1 cache, level2 cache will be in full synchronization with table rows.

Level-2 Cache:

It is a configurable cache (Not a built in cache). Third party vendors are supplying supporting jar files for level 2 cache. Level2 cache is global cache and it is visible for all the session objects of the hibernate application.
When level-2 cache is enabled the results gathered for database software will be stored in both level 1 and level 2 caches.

sessionFactory.close() –> Destroys the session factory object and releases level 2 cache.
sessionFactory.evict(args …) –> Removes pojo class object from session factory.
sessionFactory.evictQueries(args…) –> Cleans queries related data from cache.

If hibernate use same request as second request or different session objects then software tries to collects the results either from leve1/level2 caches.
There are different third party providers for level 2 cache:
  1. Swarm Cache
  2. OS Cache,
  3. EH Cache
  4. JBoss Tree Cache … etc..
Reference Books:

Related Posts Plugin for WordPress, Blogger...
© javabynataraj.blogspot.com from 2009 - 2022. All rights reserved.