使用Spring进行Hibernate二级缓存

时间:2009-01-23 19:29:02

标签: java hibernate spring jpa java-ee

我正在使用Spring + JPA + Hibernate。我正在尝试启用Hibernate的二级缓存。在我的春天applicationContext.xml我有:

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

当我跑步时,我得到错误:

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) 

所以它抱怨我没有启用二级缓存。我尝试通过添加到applicationContext.xml

来启用它
<prop key="hibernate.cache.use_second_level_cache">true</prop>

但仍然没有快乐。我也尝试将其添加到我的ehcache.xml中:

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

但它仍然无效。将provider_class更改为org.hibernate.cache.EhCacheProvider也无济于事:

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

我的实体类被注释为使用缓存

@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)

那么,我该如何启用二级缓存?

编辑:这是在bean下面的:

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

已解决:由于我正在使用LocalEntityManagerFactoryBean,因此会从META-INF/persistence.xml获取其设置。 applicationContext.xml中的我的设置甚至没有被阅读。

3 个答案:

答案 0 :(得分:13)

我没有回答这个问题,但海报自己找到答案并不明显。我正在回复他的答案:

解决

由于我正在使用LocalEntityManagerFactoryBean,因此会从META-INF/persistence.xml获取其设置。 applicationContext.xml中的我的设置甚至没有被阅读。

答案 1 :(得分:5)

试试这个:

<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>

如果您使用Maven,请将其添加到您的POM文件中:

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

或从http://ehcache.org/

下载最新的jar

答案 2 :(得分:1)

This link帮助我使用Hibernate 4的二级缓存