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

我有简单的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"/>

因此,在服务器的输出上,我可以监视执行的查询(但我不确定:如果查询在输出中可见,则表示查询已发送到数据库,或者查询已发送到entityManager,entityManager决定使用缓存和稍后将查询发送到数据库).

因此,我如何区分对象的结果是:

>直接从数据库
>直接从缓存

我将不胜感激.

最佳答案
您可以启用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查询是否从缓存或数据库获取结果 - 代码日志