首页 > Java > java教程 > 正文

如何解决JPA和Hibernate中的N 1问题?

Mary-Kate Olsen
发布: 2024-11-14 18:54:02
原创
659 人浏览过

How to Solve the N+1 Problem in JPA and Hibernate?

Tackling the N+1 Problem in JPA and Hibernate

The N+1 issue arises when excessive queries are executed to retrieve relational data. For instance, in Hibernate, an initial query fetches N records, and N additional queries are needed to retrieve associated records for each.

To resolve this problem, utilize JOIN FETCH:

List<PostComment> comments = entityManager.createQuery(
    "select pc from PostComment pc join fetch pc.post p where pc.review = :review"
)
.setParameter("review", review)
.getResultList();
登录后复制

This JOIN FETCH eager-fetches the post association, eliminating the N+1 queries.

If multiple child associations need fetching, fetch one collection in the initial query and the others with subsequent queries.

Automatic Detection

Integration testing is ideal for detecting the N+1 issue. The db-util project provides an automatic JUnit assert to validate the expected count of SQL statements generated:

@Test
public void shouldNotHaveANPlusOneQuery() {
    // code to configure and execute db-util

    Assert.assertCountOfSqlStatementsPerformed(1);
}
登录后复制

以上是如何解决JPA和Hibernate中的N 1问题?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板