@OneToOne relationship with spring data JPA, how to avoid N+1 problem when fetching a list of items?

The problem:

Imagine You have the following entities:

The Person entity:

The Passport entity:

So there’s one to one relation between Person and Passport

The Person JpaRepository :

The test:

Logs after test execution:

The PersonRepository findAll() method executed 3 queries, one to get all persons (3 in our test) and two queries to get the two passports referenced by person1 and person2 !

Imagine that we have a REST endpoint [GET /v1/persons] in our app to get all persons in a list. That endpoint uses PersonRepository’s findAll() method to return the result.

findAll() in that case will execute N + 1 queries (N is the length of the persons list), one query to get all persons and one query per person to get its passport, so to get a list with 10 000 entities, we should execute 10 001 queries ! That’s huge right ?

The solution:

To make findAll() method executes only one query instead of N + 1 :

Update the Passport definition :

Then override the findAll() method in PersonRepository or create a new JpaRepository for the Person entity (so you can use two versions of findAll()):

Now the findAll() method will execute one query instead of N +1 queries as show the new test log :

Software engineer at RTE