Stage 2 · Lesson 10 of 10
The N+1 query problem
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
- CoursePaidGrokking Relational Database Design and Modeling
Design Gurus · Intermediate · $98 one-time
The modelling and normalisation decisions that stay with a codebase for years
- CourseFreeCS50's Introduction to Databases with SQL
Harvard University · Beginner
Free course from querying through schema design, indexes, transactions and scaling
Practise
Also worth your time
- Database Indexing Explained: B-Tree, Hash, Bitmap, R-Tree, and When to Use Each (opens in a new tab)Read
B-tree and composite indexes, plus the leftmost-prefix rule that trips people up
What sits under your queries: storage engines, transactions and isolation levels