使用 Spring 休眠第二级缓存

2022-09-02 10:31:36

我正在使用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_classorg.hibernate.cache.EhCacheProvider

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

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

@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)

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

编辑:这是在豆子下面:

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

解决:由于我正在使用它,因此它从中获取其设置。我的设置甚至没有被读取。LocalEntityManagerFactoryBeanMETA-INF/persistence.xmlapplicationContext.xml


答案 1

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

解决

由于我正在使用它,因此它从中获取其设置。我的设置甚至没有被读取。LocalEntityManagerFactoryBeanMETA-INF/persistence.xmlapplicationContext.xml


答案 2

试试这个:

<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


推荐