简单的JPA findBy请求所需的时间为4分钟,而SQL查询为365毫秒 [英] Simple JPA findBy request takes 4 minutes vs 365 milliseconds of SQL Query
问题描述
我正在Spring Boot应用程序中使用JpaRepository
接口来映射没有外键的表.
I am using the JpaRepository
interface in a Spring Boot application to map a table without foreign keys.
我的pom.xml
包含:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-tools</artifactId>
<version>4.3.2.Final</version>
</dependency>
所以,我正在使用Hibernate.
So, I am using Hibernate.
我的实体看起来像这样:
My entity looks like this:
@Entity
@Table(name = "TABLE_NAME")
@NamedQuery(name = "CbmAnomalyDectOutput.findAll", query = "SELECT c FROM EntityName c")
public class EntityName implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(name = "ID_GENERATOR", sequenceName = "MY_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ID_GENERATOR")
private long id;
@Column(name = "ANOMALY_CLASS")
private String anomalyClass;
@Column(name = "ANOMALY_PROB")
private BigDecimal anomalyProb;
@Column(name = "ANOMALY_SEVERITY")
private BigDecimal anomalySeverity;
以此类推!
我创建了方法findByAnomalyClass(String anomalyClass)
.
该表包含17,050条记录,查询返回约3,000条记录.
The table contains 17,050 records and the query returns about 3,000 of them.
但是...需要4分钟!
BUT... It takes 4 minutes!!!
与SQL查询相比,执行时间缩短了很多倍.
Comparing it with SQL query, the execution time is many times shorter.
我激活了一个非常冗长的日志,并且发现对象org.hibernate.loader.Loader
是问题所在!它记录具有相同时间戳的2048行,然后记录其他145行和其他行.
I activated a very verbose log and I noticed that the object org.hibernate.loader.Loader
is the problem! It logs 2048 rows with the same timestamp, then other 145 and the the other rows.
这是关键部分. 从2048到2049的结果移动,整个执行时间变得非常非常长!
有什么建议吗?
推荐答案
- 您需要确保JPA生成的查询是您期望的查询.您可以将JPA配置为在日志文件中记录查询.
- 假设查询相同,我们可以预期响应时间大致相同.一个例外是结果集行尚未在内存中.在这种情况下,在返回结果集之前,首先需要执行查询,将其从磁盘读取到内存中.
- 取决于用Java代码处理结果集的方式,从数据库检索结果集和使用该数据完成业务逻辑之间可能要花费大量时间.您可以在调试会话中查明是否是这种情况.
这篇关于简单的JPA findBy请求所需的时间为4分钟,而SQL查询为365毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!