JPA和Hibernate中N+1问题的解决方案是什么? [英] What is the solution for the N+1 issue in JPA and Hibernate?
问题描述
我知道 N+1 问题是执行一个查询来获取 N 条记录,执行 N 条查询来获取一些关系记录.
I understand that the N+1 problem is where one query is executed to fetch N records and N queries to fetch some relational records.
但是如何在 Hibernate 中避免它呢?
But how can it be avoided in Hibernate?
推荐答案
假设我们有一个类 Manufacturer,它与 Contact 有多对一的关系.
Suppose we have a class Manufacturer with a many-to-one relationship with Contact.
我们通过确保初始查询获取加载我们需要的对象所需的所有数据来解决这个问题.一种方法是使用 HQL fetch join.我们使用 HQL
We solve this problem by making sure that the initial query fetches all the data needed to load the objects we need in their appropriately initialized state. One way of doing this is using an HQL fetch join. We use the HQL
"from Manufacturer manufacturer join fetch manufacturer.contact contact"
使用 fetch 语句.这会导致内部联接:
with the fetch statement. This results in an inner join:
select MANUFACTURER.id from manufacturer and contact ... from
MANUFACTURER inner join CONTACT on MANUFACTURER.CONTACT_ID=CONTACT.id
使用 Criteria 查询,我们可以获得相同的结果
Using a Criteria query we can get the same result from
Criteria criteria = session.createCriteria(Manufacturer.class);
criteria.setFetchMode("contact", FetchMode.EAGER);
创建 SQL :
select MANUFACTURER.id from MANUFACTURER left outer join CONTACT on
MANUFACTURER.CONTACT_ID=CONTACT.id where 1=1
在这两种情况下,我们的查询都会返回已初始化联系人的制造商对象列表.只需运行一个查询即可返回所需的所有联系人和制造商信息
in both cases, our query returns a list of Manufacturer objects with the contact initialized. Only one query needs to be run to return all the contact and manufacturer information required
这里有一个链接到问题和解决方案.
这篇关于JPA和Hibernate中N+1问题的解决方案是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!