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

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

问题描述

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

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

解决方案

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

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

SELECT * FROM Cars;

,然后为每个Car :

SELECT * FROM Wheel WHERE CarId = ?

换句话说,您对汽车有一个选择,然后有N个附加选择,其中N是汽车总数.

或者,一个人可以全力以赴并在内存中执行查找:

SELECT * FROM Wheel

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

参考: 使用Hibernate进行Java持久性 ,第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天全站免登陆