【发布时间】:2017-01-09 12:29:18
【问题描述】:
正如我在许多文章(例如here)中所读到的 - 要为给定实体启用 Hibernate 的二级缓存,我们需要通过 @org.hibernate.annotations.Cache 注释在实体上设置缓存并发策略。
@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Person {
此外,我还在一些获取此实体的查询上使用查询级缓存(使用query.setCacheable(true)),并且效果很好。
我的问题与使用 DTO 投影的自定义查询有关,因此对于这样的查询:
Query query = session.createQuery("SELECT new PersonDto(person.id, person.name) FROM Person person WHERE person.name = :name");
query.setParameter("name", name);
query.setCacheable(true);
query.uniqueResult();
我还需要为PersonDto 设置@Cache 注释吗?我尝试在没有注释的情况下运行查询,并且成功缓存了 DTO。
你能解释一下为什么我们只需要实体对象的注解而其他非实体对象不需要吗?
谢谢。
【问题讨论】:
标签: java spring hibernate jpa caching