How to Manage the caches in Hibernate by R4R Team

In the hibernate when we talk about the hibernate caching management then we need to follow some basic things which are given:

1. When pass an object to save(), update() or saveOrUpdate(), and when retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session.

2. When flush() is subsequently called, the state of that object will be synchronized with the database. 

When we want this synchronization to occur, or if processing a huge number of objects and need to manage memory efficiently, the evict() method can be used to remove the object and its collections from the first-level cache.

When we use a huge no of object that time we have to do this kind of activity as given below:

ScrollableResult cats = sess.createQuery("from Cat as cat").scroll(); //a huge result set
while ( ) {
    Cat cat = (Cat) cats.get(0);

When we do as given above in that time the Session also provides a contains() method to determine if an instance belongs to the session cache.To evict all objects from the session cache, call Session.clear(). 

For the second-level cache, there are methods defined on SessionFactory for evicting the cached state of an instance, entire class, collection instance or entire collection role.

sessionFactory.evict(Cater.class, caterId); //evict a particular Cater
sessionFactory.evict(Cater.class);  //evict all Caters
sessionFactory.evictCollection("Cater.kittens", caterId); //evict a particular collection of kittens
sessionFactory.evictCollection("Cater.kittens"); //evict all kitten collections

The CacheMode controls how a particular session interacts with the second-level cache:

1. CacheMode.NORMAL: will read items from and write items to the second-level cache
2. CacheMode.GET: will read items from the second-level cache. Do not write to the second-level cache except when updating data
3. CacheMode.PUT: will write items to the second-level cache. Do not read from the second-level cache
4. CacheMode.REFRESH: will write items to the second-level cache. Do not read from the second-level cache. Bypass the effect of hibernate.cache.use_minimal_puts forcing a refresh of the second-level cache for all items read from the database
5. To browse the contents of a second-level or query cache region, use the Statistics API:

Map cacheEntries = sessionFactory.getStatistics()

In that case we need to enable statistics and, optionally, force Hibernate to keep the cache entries in a more readable format:

1. hibernate.generate_statistics true
2. hibernate.cache.use_structured_entries true
Leave a Comment:
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!