简体   繁体   中英

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.

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.

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/

这个链接帮助我使用Hibernate 4的二级缓存

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM