通常,我使用Hibernate的 @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) 来缓存@Entity类,并且效果很好。
在JPA2中,还有另一个@Cacheable批注,该批注似乎与Hibernate的@Cache相同。为了使我的实体类独立于hibernate的包,我想尝试一下。但是我无法使其工作。每次简单的id查询仍然会命中数据库。
谁能告诉我哪里出了问题?谢谢。
实体类:
@Entity //@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) @Cacheable(true) public class User implements Serializable { // properties }
测试类别:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:app.xml"}) @TransactionConfiguration(transactionManager="transactionManager") public class UserCacheTest { @Inject protected UserDao userDao; @Transactional @Test public void testGet1() { assertNotNull(userDao.get(2L)); } @Transactional @Test public void testGet2() { assertNotNull(userDao.get(2L)); } @Transactional @Test public void testGet3() { assertNotNull(userDao.get(2L)); } }
测试结果显示每个“ get”命中数据库层(具有hibernate.show_sql = true)。
Persistence.xml:
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/> <property name="hibernate.show_sql" value="true"/> <property name="hibernate.format_sql" value="true" /> <property name="hibernate.use_outer_join" value="true"/> <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"/>
JPA代码:
@Override public T get(Serializable id) { return em.find(clazz, id); }
根据JPA 2.0规范,如果使用的需要有选择性的缓存实体@Cacheable注释,你应该到指定<shared-cache- mode>的persistence.xml(或同等javax.persistence.sharedCache.mode 创建时EntityManagerFactory)。
@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。因此,以上内容不能保证:)