I'm working on a java application which is being developed using Java (JDK 1.8), Spring MVC(Restful Web service Layer) 4.x, Hibernate 5.x, MYSQL Db and Tomcat Server 8. Everything is configured programmatically in java config and there are no XML Configuration files. I need to configure second level cache for hibernate. I'm planning to integrate EhCache with the application.
Regarding configuring Ehcache as Hibernate second level cache programatically, no this is not possible out of the box when you are using Ehcache 2.x and net.sf.ehcache.hibernate.EhCacheRegionFactory
. You will have to extend the factory class and make it configure the CacheManager
to use.
For Hibernate 5.2 with JCache, using Ehcache 3.x as provider, there is a simpler path: make sure you configure first the JCache CacheManager
and then have Hibernate use the one configured. As an alternative, you can extend the org.hibernate.cache.jcache.JCacheRegionFactory
and adapt CacheManager
and Cache
creations. The following sample can help you figure it out.
On the second point:
Spring caching is a general abstraction that can be used at all layers of your application where you decide what is cached, from which call, etc ...
Hibernate second level cache is a dedicated cache sitting between your object model and the database access. You tell the framework what to cache with which semantics but then the actual work is hidden from you.
You can certainly combine both in a single application, where you would cache higher level results such as service call results or webpages with Spring Cache and entities / query results with Hibernate 2LC. Though I would recommend to use different Cache
to well separate their content and lifecycle.