Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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.

(在对象关系映射(ORM)讨论中,通常将“ N + 1选择问题”表示为问题,并且我了解到它与必须对对象中看起来很简单的内容进行大量数据库查询有关。世界。)

Does anybody have a more detailed explanation of the problem?

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

  ask by Lars A. Brekken translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Let's say you have a collection of Car objects (database rows), and each Car has a collection of Wheel objects (also rows).

(假设您有一个Car对象(数据库行)的集合,而每个Car都有Wheel对象(也行)的集合。)

In other words, CarWheel is a 1-to-many relationship.

(换句话说, CarWheel是一对多关系。)

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:

(天真的O / R实现将执行以下操作:)

SELECT * FROM Cars;

And then for each Car :

(然后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.

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

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.

(这样可以将到数据库的往返次数从N + 1减少到2。大多数ORM工具都提供了几种防止N + 1选择的方法。)

Reference: Java Persistence with Hibernate , chapter 13.

(参考: Java持久性Hibernate ,第13章。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...