gpt4 book ai didi

java - EntityManager.getResultList() 性能缓慢

转载 作者:太空宇宙 更新时间:2023-11-04 12:59:51 26 4
gpt4 key购买 nike

我们在 Web 应用程序中使用 Hibernate + Spring boot,我们在 EntityManager 执行选择查询时遇到性能问题。该查询应返回 20 行,并且在 DBArtisan 中执行时间小于 1 秒。然而,相同的查询在代码中执行了 9 秒:

CriteriaQuery<Long> totalCriteriaQuery = criteriaBuilder.createQuery(Long.class);
Root<M> totalRoot = totalCriteriaQuery.from(modelClass);
totalCriteriaQuery.select(criteriaBuilder.count(totalRoot));
if (searchCriteria != null) {
totalCriteriaQuery.where(whereBuilder.build(searchCriteria, criteriaBuilder, totalRoot));
}
TypedQuery<Long> totalQuery = em.createQuery(totalCriteriaQuery);
contentQuery.setFirstResult(pageRequest.getOffset());
contentQuery.setMaxResults(pageRequest.getPageSize());
StopWatch stopWatch = new StopWatch();
stopWatch.start();
List<M> resultList = contentQuery.getResultList();
stopWatch.stop();
System.out.println("Nano seconds: "+ stopWatch.getNanoTime());

我正在寻找有关使用 EM 的性能的原因或任何建议。

最佳答案

如果您遇到性能不佳的情况,您应该尝试分析代码以查看性能问题的真正根源。我建议为此目的使用 JProfiler,它给出了非常清晰的结果,甚至报告调用者函数。

您是否尝试过缓存查询,当您使用 Hibernate + Spring 配置时,它也可能会有所帮助。如果您想提高性能,我建议您查看此页面 JPA Performance Tuning

附注根据我自己的经验,如果性能是您的第一选择,请尝试使用普通 JDBC 而不是 EM。

关于java - EntityManager.getResultList() 性能缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35029982/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com