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:
- Level one cache
- 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 will be kept tracked and only one update query will 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(arga …) --> 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:
- Swarm Cache
- OS Cache,
- EH Cache
- JBoss Tree Cache … etc.
No comments:
Post a Comment