如何使用Hibernate 3.5.2配置JPA 2.0以将EHCache用作二级缓存和查询缓存?

16

我发现一些关于如何配置纯Hibernate使用EHCache的说明。但我找不到任何有关如何配置JPA2.0 EntityManager使用缓存的说明。我的JPA2.0提供程序是Hibernate 3.5.2。

编辑//

@Cacheable(true)对实体来说足够吗?还是我应该使用@org.hibernate.annotations.Cache来配置实体?


2个回答

30
我发现了一些关于如何配置纯Hibernate使用EHCache的指南。但是我找不到任何有关如何配置JPA2.0 EntityManager使用缓存的说明。我的JPA2.0供应商是Hibernate 3.5.2。
配置JPA的L2缓存提供程序的方法与原始的Hibernate类似。
默认情况下,Hibernate 3.5附带EhCache 1.5(参见将Ehcache配置为二级缓存),如果您想使用Hibernate提供的官方缓存提供程序(在Maven中使用hibernate-ehcache),请声明:
<!-- This is the provider for Ehcache provided by Hibernate, using the "old" SPI -->
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.EhCacheProvider"/>

如果您想使用EhCache 2.x,您需要使用由EhCache提供的提供程序,该提供程序支持具有其 CacheRegionFactory Hibernate 3.3 / 3.5 SPI。使用:
<!-- The region factory property is the "new" property (for Hibernate 3.3 and above) -->
<property name="hibernate.cache.region.factory_class" value="net.sf.ehcache.hibernate.EhCacheRegionFactory">

例如创建,或者
<property name="hibernate.cache.region.factory_class" value="net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory"/>

强制Hibernate使用Ehcache CacheManager的单例。然后激活L2缓存和查询缓存:
<property name="hibernate.cache.use_second_level_cache" value="true"/>
<property name="hibernate.cache.use_query_cache" value="true"/>

这是关于Hibernate L2缓存设置的。

@Cacheable(true)对实体来说足够了吗?还是应该使用@org.hibernate.annotations.Cache来配置实体?

理论上,@Cacheable应该是Hibernate专有注释的替代品,并应与shared-cache-mode元素一起使用:

<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0">
  <persistence-unit name="FooPu" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    ...
    <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
    <properties>
      ...
    </properties>
  </persistence-unit>
</persistence>

但正如这个之前的问题中提到的那样,最初的实验并不成功(可能与HHH-5303有关,我不能确定,我没有深入调查)。因此,我建议坚持使用专有注释。

参考资料

  • Hibernate EntityManager 参考指南
  • JPA 2.0 规范
    • 第3.7.1节“shared-cache-mode元素”
    • 第11.1.7节“Cacheable注释”

资源

相关问题


3

在 persistence.xml 文件中,您可以指定以下属性:

<property name="hibernate.cache.region.factory_class"
       value="org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory" />

并使其生效:

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

在 Hibernate 3.5.2 中,<property name="hibernate.cache.provider_class" value="org.hibernate.cache.EhCacheProvider" /> 的类 org.hibernate.cache.EhCacheProvider 不存在。 - Piotr Gwiazda
请单独下载EhCache并将其放置在您的类路径上。我的答案中的值不是“org.hibernate..”。 - Bozho
使用Hibernate 4.1时,以上所有配置都无效。出现java.lang.NoClassDefFoundError: org/hibernate/cache/TimestampsRegion的错误。这在Hibernate 3中存在,但已在Hibernate 4中删除。有任何意见吗? - R-JANA

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接