ProAnswers.org

n+1 select problem?

Can anyone tell me about this n=1 selects problem? This is mentioned in O/R-mapping discussions.

 Best guide is [Java Persistence with Hibernate](http://www.manning.com/bauer2/), chapter 13. 



Let's say you have a collection of Car objects (database rows), and each Car has a collection of Wheel objects (database 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;

/* 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.