Spring JPA – 读取数据以及关联关系 – 性能改进

huangapple go评论65阅读模式
英文:

Spring JPA - Reading data along with relations - performance improvement

问题

我正在使用Spring JPA从表中读取数据。
这个实体对象与其他六个表之间存在一对多的关系。
所有的表总共有20,000条记录。
我正在使用以下查询从数据库中获取数据。

SELECT * FROM A WHERE ID IN (SELECT ID FROM B WHERE COL1 = '?')

表A与其他6个表存在关系。
Spring JPA花费大约30秒的时间从数据库中读取这些数据。
有任何改进数据提取时间的想法吗?

我在这里使用的是原生查询,并且我正在寻找能够优化数据提取时间的查询重写方法。
请给出建议,谢谢。

英文:

I am reading data from a table using Spring JPA.
This Entity object has one-to-many relationship to other six tables.
All tables together has 20,000 records in them.
I am using below query to fetch data from DB.

SELECT * FROM A WHER ID IN (SELECT ID FROM B WHERE COL1 = '?')

A table has relationship to other 6 tables.
Spring JPA is taking around 30 seconds of time to read this data from DB.
Any idea to improve the data fetch time here.

I am using native Queries here and i am looking for query rewriting that will optimize the data fetch time.
Please suggest thanks.

答案1

得分: 1

以下是已翻译的内容:

你可能需要考虑以下内容来确定根本原因:

  • 检查是否出现了 n+1 查询问题。您的查询可能会对每个连接表调用 n 个查询,其中 n 是与连接表关联的数量。您可以通过设置 spring.jpa.show-sql=true 来检查这一点。
  • 如果您发现问题是 n+1,那么您需要设置适当的 FetchMode,请参阅 https://www.baeldung.com/hibernate-fetchmode 以获取有关使用不同 FetchMode 的详细说明。
  • 如果不是 n+1 查询问题,您可能需要使用 EXPLAIN 命令检查生成的查询的性能。通常,在非索引列上使用 IN 子句会影响性能。

因此,设置 spring.jpa.show-sql=true,检查生成的查询并运行以调试和优化您的代码或查询。

英文:

You might need consider below to identify the root cause:

  • Check if you are ending up with n+1 query issue. Your query might end up calling n queries for each join table, where n is no. of associations with the join table. You can check this by setting spring.jpa.show-sql=true
  • If you see the issue as n+1 then you need set appropriate FetchMode, refer https://www.baeldung.com/hibernate-fetchmode for detailed explanation of using different FetchModes.
  • If it is not n+1 query issue you might need to check the performance of the genarated queries using EXPLAIN command. Usually IN clause on a non indexed columns have performance impact.

So set spring.jpa.show-sql=true and check queries generated and run to debug and optimize your code or query.

huangapple
  • 本文由 发表于 2020年9月2日 23:57:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/63709187.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定