Backend development

Stage 2 · Lesson 10 of 10

The N+1 query problem

Relational databases and SQL

JPA loads collections lazily by default, only when you first touch them. That is where the problem comes from. You fetch 50 orders and walk each order's items, in a loop or while turning them into JSON.

50 extra selects run. @ManyToOne is eager by default, which causes its own surprises. So mark relations LAZY and fetch what you need on purpose.

Fix N+1 with JOIN FETCH in a JPQL query, or an @EntityGraph on the method. Or use a DTO projection, a query that selects only the fields the response needs. Turn on SQL logging in development with spring.jpa.show-sql or statistics.

Common trap, turned on by default in , which lets lazy loads run unnoticed while the response is being built.

A question to check yourself, an AI practice session and 1 cheat sheet entry come with the full roadmap. Unlock

Resources for this stage

Start with· follow one of these

Practise

Also worth your time

Mark this stage as not done?