EhCache as second level cache implementation

We now understand how the caching in Hibernate works on a high level. So the second level cache doesn’t get enabled by default, but needs to be turned on explicitly in our application. So here is how we can do it.

Make sure we have the needed pom file entries for ehCache –

Turn on the second level cache in your hibernateContext.xml (or hibernateCfg.xml) file as –

Now make sure the ehCache.xml file is added to your application’s classpath and has the content something like below –

  • hibernate.cache.use_second_level_cache – To enable second level cache
  • hibernate.cache.use_query_cache – To enable query caching
  • hibernate.cache.region.factory_class – To define the factory or cacheProvider class for second level caching
  • net.sf.ehcache.configurationResourceName – To define the EhCache configuration file name and location

We earlier used to specify the cacheProvider using the property hibernate.cache.provider_class to be org.hibernate.cache.EhCacheProvider, which has now been deprecated.

timeToLiveSeconds – The second level cache automatically gets invalidated and updated whenever an entity is updated/deleted via Hibernate. However, if the database is updated directly without involving Hibernate, the second level cache won’t get invalidated automatically until ‘timeToLiveSeconds’ duration is reached.

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.