根据JPA 2.0规范,如果使用的需要有选择性的缓存实体
@Cacheable注释,你应该到指定
<shared-cache-mode>的
persistence.xml(或同等
javax.persistence.sharedCache.mode
创建时
EntityManagerFactory)。
下面是
persistence.xml带有相关元素和属性的样本:
<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> ... <property name="hibernate.cache.provider_class" value="org.hibernate.cache.SingletonEhCacheProvider"/> <property name="hibernate.cache.use_second_level_cache" value="true"/> <property name="hibernate.cache.use_query_cache" value="true"/> </properties> </persistence-unit></persistence>
请注意,我已经看到至少一个与缓存有关的问题HHH-5303。因此,以上内容不能保证:)
参考文献
- Hibernate EntityManager参考指南
- 2.2.1包装
- JPA 2.0规范
- 第3.7.1节“共享缓存模式元素”
- 第11.1.7节“可缓存的注释”



