我找到了一些说明如何配置纯休眠以使用 EHCache。但我找不到任何说明如何配置 JPA2.0 EntityManager 以使用缓存。 Hibernate 3.5.2 是我的 JPA2.0 提供者。
使用 JPA 配置 L2 缓存提供程序的方式与原始 Hibernate 类似。
默认情况下,Hibernate 3.5 附带 EhCache 1.5(请参阅 Configure Ehcache as a Second Level Cache),如果您想使用 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 提供的提供程序,该提供程序支持 新 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>
但是正如this previous question中提到的,最初的实验并没有成功(可能与HHH-5303有关,我不能说,我没有调查那么多)。所以我建议坚持使用专有注释。
参考文献
- Hibernate EntityManager 参考指南
- JPA 2.0 规范
- 第 3.7.1 节“共享缓存模式元素”
- 第 11.1.7 节“可缓存注释”
资源
相关问题