【问题标题】:JPA fires N+1 select queries upon transaction commitJPA 在事务提交时触发 N+1 选择查询
【发布时间】:2020-03-04 14:26:38
【问题描述】:

我正在执行一项性能调整任务,我发现 JPA N+1 查询是性能问题的根本原因。我将查询更改为使用 JOIN FETCH 来解决 N+1 问题。对于 OneToMany 映射及其单向,所有实体关系都使用 FetchType.LAZY 进行映射, 表示我没有在子实体上设置 ManyToOne。

现在,如果 N+1,则触发单个 JOIN 查询。但是当事务性 ejb 方法返回时,突然所有 N+1 个查询都被触发了。当我调试时,我发现了一种行为,即如果我更改事务边界,则在退出该事务方法时会触发 N+1 个查询。

我已经面对这个问题两天了。我真的很累,尝试了所有方法。我尝试了条件查询、JPQL 查询、删除事务(导致另一个异常)

我错过了什么吗?因为 N+1 是非常流行的问题,当然解决方案也是众所周知的。

我使用 OpenJPA 作为实现 (JPA2.1) 和 DB2 作为数据库。

非常感谢您对此的任何帮助

【问题讨论】:

    标签: hibernate jpa db2 openjpa


    【解决方案1】:

    一般来说,Db2 编译器会根据当前的统计数据重写性能更好的 select 语句。 以下是 Db2 编译器工作原理的 7 个内部步骤。

    SQL 和 XQuery 编译过程
    https://www.ibm.com/support/knowledgecenter/SSEPGG_11.5.0/com.ibm.db2.luw.admin.perf.doc/doc/c0005292.html

    The SQL and XQuery compiler performs several steps to produce an access plan that can be executed.
    
    1.  Parse query
    2.  Check semantics
    3.  Rewrite query
    4.  Pushdown analysis (federated databases only)
    5.  Optimize access plan
    6.  Remote SQL generation (federated databases only)
    7.  Generate executable code
    

    换句话说,即使我们发送一个编写良好的选择语句,Db2 也可能将其重写为性能更好的查询。 因此,对于性能调优任务,建议从以下页面开始:

    性能概览
    https://www.ibm.com/support/knowledgecenter/en/SSEPGG_11.5.0/com.ibm.db2.luw.admin.perf.doc/doc/c0005414.html#c0005414 这里被剪掉了。

    Performance refers to the way that a computer system behaves in response to a 
    particular workload. Performance is measured in terms of system response time, 
    throughput, and resource utilization.
    Performance is also affected by:
    
        The resources that are available on the system
        How well those resources are used and shared
    

    如果我没有正确理解您的问题,请忽略。

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-25
      • 2011-06-23
      • 2016-08-21
      • 2014-07-19
      • 2011-10-08
      • 2021-10-09
      • 1970-01-01
      相关资源
      最近更新 更多