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, Car → Wheel 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 WheelThis 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(对象关系映射)中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-05 01:39