Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Please explain N+1 Problem in easy way with example

 
jacob deiter
Ranch Hand
Posts: 584
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please explain N+1 Problem in easy way with example
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
amit punekar
Ranch Hand
Posts: 544
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Paul,
I found this explanation very brief and easy to understand.
Thanks
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are welcome. Glad it was useful.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic