什么是“N+1选择问题"?在 ORM(对象关系映射)中? [英] What is the "N+1 selects problem" in ORM (Object-Relational Mapping)?

查看:31
本文介绍了什么是“N+1选择问题"?在 ORM(对象关系映射)中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

N+1 选择问题"通常在对象关系映射 (ORM) 讨论中被表述为一个问题,我知道这与必须为看似简单的事情进行大量数据库查询有关在对象世界中.

有人对这个问题有更详细的解释吗?

解决方案

假设您有一组 Car 对象(数据库行),并且每个 Car 都有一个Wheel 对象(也是行)的集合.换句话说,CarWheel 是一对多的关系.

现在,假设您需要遍历所有汽车,并为每个汽车打印出车轮列表.简单的 O/R 实现将执行以下操作:

SELECT * FROM Cars;

然后对于每个Car:

SELECT * FROM Wheel WHERE CarId = ?

换句话说,你有一个选择 Cars,然后 N 个额外的选择,其中 N 是汽车的总数.

或者,可以获取所有轮子并在内存中执行查找:

SELECT * FROM Wheel

这将到数据库的往返次数从 N+1 减少到 2.大多数 ORM 工具为您提供了几种防止 N+1 选择的方法.

参考:Java 持久化与 Hibernate,第 13 章.

The "N+1 selects problem" is generally stated as a problem in Object-Relational mapping (ORM) discussions, and I understand that it has something to do with having to make a lot of database queries for something that seems simple in the object world.

Does anybody have a more detailed explanation of the problem?

解决方案

Let's say you have a collection of Car objects (database rows), and each Car has a collection of Wheel objects (also rows). In other words, CarWheel is a 1-to-many relationship.

Now, let's say you need to iterate through all the cars, and for each one, print out a list of the wheels. The naive O/R implementation would do the following:

SELECT * FROM Cars;

And then for each Car:

SELECT * FROM Wheel WHERE CarId = ?

In other words, you have one select for the Cars, and then N additional selects, where N is the total number of cars.

Alternatively, one could get all wheels and perform the lookups in memory:

SELECT * FROM Wheel

This reduces the number of round-trips to the database from N+1 to 2. Most ORM tools give you several ways to prevent N+1 selects.

Reference: Java Persistence with Hibernate, chapter 13.

这篇关于什么是“N+1选择问题"?在 ORM(对象关系映射)中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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