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

Pio*_*zda 16 orm hibernate ehcache second-level-cache jpa-2.0

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

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

Pas*_*ent 30

我找到了一些如何配置纯hibernate以使用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"/>
Run Code Online (Sandbox Code Playgroud)

如果你想使用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">
Run Code Online (Sandbox Code Playgroud)

例如创造,或

<property name="hibernate.cache.region.factory_class" value="net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory"/>
Run Code Online (Sandbox Code Playgroud)

强制Hibernate使用单个Ehcache CacheManager.

然后激活L2缓存和查询缓存:

<property name="hibernate.cache.use_second_level_cache" value="true"/>
<property name="hibernate.cache.use_query_cache" value="true"/>
Run Code Online (Sandbox Code Playgroud)

这是针对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>
Run Code Online (Sandbox Code Playgroud)

但正如前一个问题所述,最初的实验并未成功(可能与HHH-5303有关,我不能说,我没有那么多调查).所以我建议坚持使用专有注释.

参考

  • Hibernate EntityManager参考指南
  • JPA 2.0规范
    • 第3.7.1节"共享缓存模式元素"
    • 第11.1.7节"可缓存的注释"

资源

相关问题