16

我找到了一些说明如何配置纯休眠以使用 EHCache。但我找不到任何说明如何配置 JPA2.0 EntityManager 以使用缓存。Hibernate 3.5.2 是我的 JPA2.0 提供者。

编辑//@Cacheable(true)对于实体来说足够了吗?或者我应该使用@org.hibernate.annotations.Cache来配置实体?

4

2 回答 2

30

我找到了一些说明如何配置纯休眠以使用 EHCache。但我找不到任何说明如何配置 JPA2.0 EntityManager 以使用缓存。Hibernate 3.5.2 是我的 JPA2.0 提供者。

使用 JPA 配置 L2 缓存提供程序的方式类似于原始 Hibernate。

默认情况下,Hibernate 3.5 附带 EhCache 1.5(请参阅将Ehcache 配置为二级缓存),如果您想使用 Hibernate 提供的官方缓存提供程序(hibernate-ehcache如果您使用 Maven),请声明:

<!-- 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 提供的提供程序,该提供程序支持的Hibernate 3.3/3.5 SPI 及其CacheRegionFactory)。采用:

<!-- 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 节“共享缓存模式元素”
    • 第 11.1.7 节“可缓存注释”

资源

相关问题

于 2010-09-09T10:05:32.457 回答
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" />
于 2010-09-09T07:57:05.410 回答