JPA和Hibernate中的N + 1问题的解决方案是什么? [英] What is the solution for the N+1 issue in JPA and Hibernate?

查看:131
本文介绍了JPA和Hibernate中的N + 1问题的解决方案是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,N + 1问题是执行一个查询来获取N个记录和N个查询以获取一些关系记录的地方。



但是它怎么可能是在Hibernate中避免?

解决方案

假设我们有一个与Contact有多对一关系的类制造商。



我们通过确保初始查询获取所需的所有数据来加载我们需要的对象,以适当的初始化状态来解决此问题。这样做的一种方法是使用HQL提取连接。我们使用HQL

 从制造商制造商加入获取manufacturer.contact联系人

与fetch语句。这导致了内部连接:

 从制造商处选择MANUFACTURER.id并从$ b $中选择联系...制造商内部连接请联系MANUFACTURER.CONTACT_ID = CONTACT.id 

使用Criteria查询,我们可以从

  Criteria criteria = session.createCriteria(Manufacturer.class); 
criteria.setFetchMode(contact,FetchMode.EAGER);

它创建了SQL:

 从MANUFACTURER中选择MANUFACTURER.id在
上留下外部联接联系人MANUFACTURER.CONTACT_ID = CONTACT.id其中1 = 1

在这两种情况下,我们的查询都会返回一个制造商对象列表,其中联系人已初始化。只需要运行一个查询即可返回所有需要的联系信息和制造商信息

有关详细信息,请参阅问题解决方案


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.

But how can it be avoided in Hibernate?

解决方案

Suppose we have a class Manufacturer with a many-to-one relationship with Contact.

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"

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

Using a Criteria query we can get the same result from

Criteria criteria = session.createCriteria(Manufacturer.class);
criteria.setFetchMode("contact", FetchMode.EAGER);

which creates the 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

for further information here is a link to the problem and the solution

这篇关于JPA和Hibernate中的N + 1问题的解决方案是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆