java - 如何检查(调试)JPA 查询是否从缓存或数据库获取结果

标签 java jpa caching eclipselink

我有简单的 JPA 查询

  Query query = getEntityManager().createQuery("SELECT pn FROM ProductsNames pn"
            + " WHERE pn.languages = :language"
            + " ORDER BY pn.products.id ASC");
    query.setParameter("language", language);
  return query.getResultList();

如何检查这些方法的结果是从缓存返回对象列表还是直接从数据库返回对象列表?

在 persistence.xml 中我设置了以下参数:

 <property name="eclipselink.logging.level.sql" value="FINE"/>

因此,在服务器的输出上,我可以监视执行的查询(但我不确定 - 如果查询在输出上可见,则意味着查询已发送到数据库,或者意味着查询已发送到实体管理器,并且实体管理器决定使用缓存,然后将查询发送到数据库)。

那么我如何区分对象的结果来自:

  • 直接来自数据库
  • 直接从缓存

我将感谢您的帮助。

最佳答案

您可以启用Performance Monitoring :

<property name="eclipselink.profiler" value="PerformanceMonitor"/>

因此,您可以多次执行查询并访问 some cache statistics ,例如查询命中缓存的次数:

Integer cacheHits = (Integer)((PerformanceMonitor)session.getProfiler())
    .getOperationTimings()
    .get(SessionProfiler.CacheHits);

如果您想在更复杂的场景中收集更多详细信息,PerformanceMonitor 已经为您做到了这一点:

The performance monitor will output a dump of cumulative statistics every minute to the EclipseLink log.

The statics contains three sets of information:

  • Info: Statistics that are constant informational data, such as the session name, or time of login.
  • Counter: Statistics that are cumulative counters of total operations, such as cache hits, or query executions.
  • Timer: Statistics that are cumulative measurements of total time (in nano seconds) for a specific type of operation, reading, writing, database operations. Statistics are generally grouped in total and also by query type, query class, and query name.

Counters and timers are generally recorded for the same operations, so the time per operation could also be calculated.

关于java - 如何检查(调试)JPA 查询是否从缓存或数据库获取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38438568/

相关文章:

java - struts 注释@Result 是否应该只在类级别?

java - 如何实现一种方法来查找 5x5 矩阵中每行和每列的最大元素?

asp.net - 在用户控件和 VaryByControl 中使用缓存

java - 为什么 iBATIS 会给出过时的结果,即使禁用了缓存?

java - Caffeine Expiry 中如何设置多个过期条件?

java - 使用 OpenSSL 验证 Java 签名类签名

java - preparedStatement.getString() 方法不适用于嵌套 sql 查询

java - 使用 Spring Data 通过实体 ID 从实体获取嵌入式对象

使用JPA的GWT

java - Spring Controller 使我的 CRUD 操作失败,对此该怎么办?