Steve Kuo
Steve Kuo

Reputation: 63054

Hibernate second level cache with Spring

I'm using Spring + JPA + Hibernate. I'm trying to enable Hibernate's second level cache. In my Spring's applicationContext.xml I have:

<prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.SingletonEhCacheProvider</prop>
<prop key="hibernate.cache.provider_configuration_file_resource_path">/ehcache.xml</prop>

When I run I get the error:

Caused by: org.hibernate.HibernateException: Could not instantiate cache implementation
     at org.hibernate.cache.CacheFactory.createCache(CacheFactory.java:64)

Caused by: org.hibernate.cache.NoCachingEnabledException: Second-level cache is not enabled for usage [hibernate.cache.use_second_level_cache | hibernate.cache.use_query_cache]
     at org.hibernate.cache.NoCacheProvider.buildCache(NoCacheProvider.java:21) 

So it's complain I don't have second level cache enabled. I attempt to enable it by adding to my applicationContext.xml:

<prop key="hibernate.cache.use_second_level_cache">true</prop>

But still no joy. I also tried adding this to my ehcache.xml:

<property name="hibernate.cache.use_second_level_cache">true</property>

But it still doesn't work. Changing the provider_class to org.hibernate.cache.EhCacheProvider doesn't help either:

<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>

My entity classes are annotated to use caching

@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)

So, how do I enable second level cache?

Edit: This is under the bean:

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">

Resolved: Since I'm using LocalEntityManagerFactoryBean it gets its settings from META-INF/persistence.xml. My settings in applicationContext.xml weren't even being read.

Upvotes: 20

Views: 52784

Answers (3)

Mainguy
Mainguy

Reputation: 1659

I didn't answer this, but it's not obvious that the poster found the answer himself. I'm reposting his answer:

Resolved

Since I'm using LocalEntityManagerFactoryBean it gets its settings from META-INF/persistence.xml. My settings in applicationContext.xml weren't even being read.

Upvotes: 13

Deepak Kashyap
Deepak Kashyap

Reputation: 11

This link helped me for using second level cache with Hibernate 4

Upvotes: 1

Bitmap
Bitmap

Reputation: 12538

Try this:

<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.max_fetch_depth">4</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</prop>

And if you are using Maven add this to your POM file:

<dependency>
  <groupId>net.sf.ehcache</groupId>
  <artifactId>ehcache-core</artifactId>
  <version>2.3.0</version>
</dependency>

Or download the latest jar from http://ehcache.org/

Upvotes: 5

Related Questions