by R4R Team

When the second-level cache is activated “Packaging” and the Hibernate Annotations reference documentation), Hibernate ensures it is used and properly updated. You can however adjust these settings by passing two properties:

1. javax.persistence.cache.retrieveMode which accepts CacheRetrieveMode values
2. javax.persistence.cache.storeMode which accepts CacheStoreMode values

CacheRetrieveMode controls how Hibernate accesses information from the second-level cache: USE which is the default or BYPASS which means ignore the cache. CacheStoreMode controls how Hibernate pushes information to the second-level cache: USE which is the default and push data in the cache when reading from and writing to the database, BYPASS which does not insert new data in the cache (but can invalidate obsolete data) and REFRESH which does like default but also force data to be pushed to the cache on database read even if the data is already cached.

You can set these properties:

1. on a particular EntityManager via the setProperty method
2. on a query via a query hint (setHint method)
3. when calling find() and refresh() and passing the properties in the appropriate Map
4. JPA also introduces an API to interrogate the second-level cache and evict data manually.

Cache cache = entityManagerFactory.getCache();

if ( cache.contains(User.class, userId) ) {
   //load it as we don't hit the DB
}

cache.evict(User.class, userId); //manually evict user form the second-level cache
cache.evict(User.class); //evict all users from the second-level cache
cache.evictAll(); //purge the second-level cache entirely
Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in 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!