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

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

问题描述

我知道N + 1问题是执行一个查询以获取N个记录和N个查询来获取一些关系记录。



但是如何才能避免在Hibernate?

解决方案

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

我们通过确保初始查询获取在适当初始化状态下加载所需对象所需的所有数据来解决此问题。一种方法是使用HQL提取连接。我们使用制造商制造商加入fetch制造商的HQL

 联系
使用fetch语句

这将导致内部连接:

 从制造商中选择制造商。从... 
制造商内部联接联系人在MANUFACTURER.CONTACT_ID = CONTACT.id

使用条件查询,我们可以从

 条件标准= session.createCriteria(Manufacturer.class); 
criteria.setFetchMode(contact,FetchMode.EAGER);

创建SQL:

 从制造商选择制造商。从外部加入联系人
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

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

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