简体   繁体   English

错过了休眠一级缓存

[英]Hibernate first level cache is missed

I'm a newbie to JPA/Hibernate first level caching. 我是JPA / Hibernate一级缓存的新手。

I have the following repository class 我有以下存储库类

Each time I call the findByState method(within the same transaction), I see the hibernate sql query being output onto the console 每次我调用findByState方法(在同一事务中)时,我都会看到将休眠SQL查询输出到控制台上

public interface PersonRepository extends JpaRepository<PersonEntity, id> {

    @Query("select person from PersonEntity p where name= (?1)")
    List<PersonEntity> findByState(String state);
    ....
}

I expected the results to be cached by the first level cache and the database not be repeatedly queried. 我希望结果将由第一级缓存来缓存,并且不会重复查询数据库。

What am I doing wrong? 我究竟做错了什么?

There is often a misunderstanding about caching. 关于缓存通常会有误解。

Hibernate does not cache queries and query results by default. 默认情况下,Hibernate不缓存查询和查询结果。 The only thing the first level cache is used is when you call EntityManger.find() you will not see a SQL query executing. 使用一级缓存的唯一一件事是,当您调用EntityManger.find()您将看不到执行SQL查询。 And the cache is used to avoid object creation if the entity is already loading. 如果实体已经加载,则使用缓存来避免创建对象。

What you are looking for is called "query cache". 您正在寻找的被称为“查询缓存”。

This can be enabled by setting hibernate.cache.use_query_cache=true 可以通过设置hibernate.cache.use_query_cache=true来启用

Please read more about this topic in the official documentation: 请在官方文档中阅读有关此主题的更多信息:

https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#caching-query https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#caching-query

The query will always go to the database. 查询将始终转到数据库。 The first level cache will only contain the constructed entities. 一级缓存将仅包含构造的实体。 Its purpose is to ensure that the same db id is mapped to the same entity object (within a session) Its also possible to use a query cache. 其目的是确保将相同的数据库ID映射到相同的实体对象(在会话内)。使用查询缓存也是可能的。 You have to enable per query. 您必须启用每个查询。 Check the docs https://docs.jboss.org/hibernate/core/4.0/devguide/en-US/html/ch06.html 检查文档https://docs.jboss.org/hibernate/core/4.0/devguide/en-US/html/ch06.html

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

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