简体   繁体   English

用于数据传输对象 (DTO) 投影的 Hibernate 二级缓存

[英]Hibernate second level cache for data transfer object (DTO) projection

As I have read in many articles (eg here ) - to enable Hibernate's second level cache for given entity we need to set cache concurrency strategy on entity via @org.hibernate.annotations.Cache annotation.正如我在许多文章(例如这里)中读到的那样 - 要为给定实体启用 Hibernate 的二级缓存,我们需要通过@org.hibernate.annotations.Cache注释在实体上设置缓存并发策略。

@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Person {

Besides I also use query-level cache (using query.setCacheable(true) ) on some queries that fetches this entity and it works well.此外,我还在一些获取此实体的查询上使用查询级缓存(使用query.setCacheable(true) ),并且效果很好。

My question relates to custom queries that uses DTO projection, so for the queries like this:我的问题与使用 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();

Do I need to set @Cache annotation also for PersonDto ?我是否需要设置@Cache注释也为PersonDto I have tried to run the query without the annotation and the DTO was successfully cached.我尝试在没有注释的情况下运行查询,并且 DTO 已成功缓存。

Could you explain why do we need the annotation for entity objects only and other non-entity objects does not require that?你能解释一下为什么我们只需要实体对象的注释而其他非实体对象不需要吗?

Thanks.谢谢。

I'm not 100% on this, but you are manually setting cacheable to true for the query.我不是 100% 对此,但你手动设置cacheabletrue为查询。

The annotation on Person is the equivalent for an entity. Person上的注释相当于实体。

I wouldn't think of it as PersonDTO being cached in this instance.我不会认为它是在这种情况下缓存的PersonDTO If you were to write another query saying select new PersonDTO(person.id, person.name) from Person person where person.id = 10 , I don't think it will look into your cache to see if a PersonDTO with id == 10 exists;如果您要编写另一个查询,说select new PersonDTO(person.id, person.name) from Person person where person.id = 10 ,我认为它不会查看您的缓存以查看是否有 id == 的 PersonDTO 10 个存在; whereas, the Entitys cache would because it understands they are the same thing.而实体缓存会因为它知道它们是同一件事。

I would think of it as the query itself is being cached (meaning if ran again before TTL then cached results would occur).我会认为它是查询本身被缓存(意味着如果在 TTL 之前再次运行,则会出现缓存结果)。 It's caching the fact that you ran this query with a certain name parameter, not that a PersonDTO with that name exists in the cache.它缓存了您使用某个name参数运行此查询的事实,而不是缓存中存在具有该名称的 PersonDTO。 Does that make sense?那有意义吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM