【发布时间】:2011-04-09 12:05:01
【问题描述】:
通常,我使用 Hibernate 的 @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) 来缓存 @Entity 类,它运行良好。
在 JPA2 中,还有另一个 @Cacheable 注释,它似乎与 Hibernate 的 @Cache 功能相同。为了让我的实体类独立于hibernate的包,我想试一试。但我不能让它工作。每次一个简单的 id 查询仍然命中 DB。
谁能告诉我哪里出错了?谢谢。
实体类:
@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);
}
【问题讨论】:
标签: hibernate orm jpa caching jpa-2.0