首页 > 解决方案 > 无法理解查询缓存和 L2C 在休眠中的工作方式

问题描述

我将 Hazelcast 配置为 Hibernate 的 L2C。然后使用带有查询缓存提示的休眠查询生成器发出第一个请求,我得到了:

org.hibernate.engine.internal.StatisticalLoggingSessionEventListener:258 - Session Metrics {
    3263961 nanoseconds spent acquiring 1 JDBC connections;
    401548 nanoseconds spent releasing 1 JDBC connections;
    4244272 nanoseconds spent preparing 1 JDBC statements;
    6266312446 nanoseconds spent executing 1 JDBC statements;
    0 nanoseconds spent executing 0 JDBC batches;
    60891580391 nanoseconds spent performing 641667 L2C puts;
    0 nanoseconds spent performing 0 L2C hits;
    8550 nanoseconds spent performing 1 L2C misses;
    0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);
    0 nanoseconds spent executing 0 partial-flushes (flushing a total of 0 entities and 0 collections)
}

得到了 L2C。当我做第二个请求时,我得到了大量的通过 id 查找的选择查询。

Hazelcast、Hibernate 的配置很简单,没有什么复杂的。

实体是连接表继承。

@Cache(usage = CacheConcurrencyStrategy.READ_WRITE) 用于超类的注解。

检查 Vlad Mihalcea 文章:https ://vladmihalcea.com/hibernate-query-cache-n-plus-1-issue - 避免 n+1 问题的建议并不完全适合我的情况。

预计会在第二次请求时从缓存中获取结果,但似乎我不明白查询缓存是如何工作的。有人可以逐步解释查询缓存的工作原理吗?

标签: hibernatecachingsecond-level-cachequery-cache

解决方案


Hibernate 不会将查询结果作为一个整体存储在“查询”区域中;它而是存储一组 id,其中实体位于其他“实体”区域。

我的猜测:如果某些配置错误并且 Hazelcast 不存储实体本身,则可能虽然从查询缓存中知道条目 ID 列表,但它会一个接一个地加载实际实体。

执行查询并检查缓存区域的大小。


推荐阅读