aspose file tools*
The moose likes JDBC and the fly likes Please explain N+1 Problem in easy way with example Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Please explain N+1 Problem in easy way with example" Watch "Please explain N+1 Problem in easy way with example" New topic
Author

Please explain N+1 Problem in easy way with example

jacob deiter
Ranch Hand

Joined: Apr 02, 2008
Posts: 576
Please explain N+1 Problem in easy way with example
Paul Sturrock
Bartender

Joined: Apr 14, 2004
Posts: 10336

I don't want to seem rude, but this is the sort of question the briefest search would have answered. It's always worth doing a bit of hunting for an answer before posting a question; you'll probably get your answer much quicker.

The N+1 problem exists where a coder takes a somewhat naive approach to accessing relational data. Imagine you have a data access object to manage a User and another one to manage their Roles and these map to two tables (user and role) with a one to many relationship between them. You could have a method called getUsers that queries for users based on some criteria. As part of that method it could also get the Roles for each user from the other DAO. This is where the n+1 problem occurs, because you would have one query to get the Users the n queries to gets roles for each user (e.g. by running select *from roles where user_id = ? ). In pseudo code it would look something like this:



People more used to working in relational databases will spot that this could be better done with one query, probably by using a join to the roles table in the first query.


JavaRanch FAQ HowToAskQuestionsOnJavaRanch
amit punekar
Ranch Hand

Joined: May 14, 2004
Posts: 515
Hi Paul,
I found this explanation very brief and easy to understand.
Thanks
Paul Sturrock
Bartender

Joined: Apr 14, 2004
Posts: 10336

You are welcome. Glad it was useful.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Please explain N+1 Problem in easy way with example