【问题标题】:Hibernate second level cache for data transfer object (DTO) projection用于数据传输对象 (DTO) 投影的休眠二级缓存
【发布时间】: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


    【解决方案1】:

    我对此不是 100%,但您手动将 cacheable 设置为 true 以进行查询。

    Person 上的注解等同于实体。

    我不会认为 PersonDTO 在这种情况下被缓存。如果您要编写另一个查询select new PersonDTO(person.id, person.name) from Person person where person.id = 10,我认为它不会查看您的缓存以查看是否存在 id == 10 的 PersonDTO;而实体缓存会因为它理解它们是同一事物。

    我会将其视为查询本身正在被缓存(这意味着如果在 TTL 之前再次运行,则会出现缓存结果)。它缓存了您使用某个 name 参数运行此查询的事实,而不是缓存中存在具有该名称的 PersonDTO。这有意义吗?

    【讨论】:

    • 感谢您的解释,这对我来说很有意义:)
    猜你喜欢
    • 2020-09-05
    • 2010-10-20
    • 1970-01-01
    • 2017-12-11
    • 2017-10-17
    • 1970-01-01
    • 2020-01-05
    • 2019-04-02
    相关资源
    最近更新 更多