N+1 is one of the most famous question among java developers. It will give some performance issue if you where working on a large project. So it's better to resolve it using some below techniques.

Suppose you have number of students in a college and every students have some number of books.

so one to many relation is between student and books.

Now suppose that you have to iterate through the collection of student and display all the books name he have. So the query will looks like this

Here you have 1 select statement for the student and if you have n number of students you have to fire n more query to select the books. So at the last you have to put n+1 select statement in order to perform this operation.

Now the next question is

Using join fetching(it will join the parent and children and fetch all the information in a single statement) we can able to solve n+1 problem.

Now our next query will look like this

**What is n+1 problem ?***Ans*: I am taking one example to let you understand that what n+1 problem is.Suppose you have number of students in a college and every students have some number of books.

so one to many relation is between student and books.

Now suppose that you have to iterate through the collection of student and display all the books name he have. So the query will looks like this

```
"select * from Students"
"select * from Books where studentId=?"
```

Here you have 1 select statement for the student and if you have n number of students you have to fire n more query to select the books. So at the last you have to put n+1 select statement in order to perform this operation.

Now the next question is

**how to solve it ?**Using join fetching(it will join the parent and children and fetch all the information in a single statement) we can able to solve n+1 problem.

Now our next query will look like this

```
"from Students s join fetch s.Books b"
```

## No comments:

## Post a Comment