Hibernate N+1 Query Problem
Fast recall
Quick revision
Core answer
Whether you recognise the most common JPA performance bug and can both detect and fix it
Not noticing N+1 because tests run on tiny datasets, or 'fixing' it by switching everything to EAGER
Show you detect N+1 with show-sql and fix it selectively with JOIN FETCH, @EntityGraph, or @BatchSize
Interview-ready guide
Interview answer
An order list may be fetched with one SELECT. If rendering each order then initializes its customer or items with a separate SELECT, 100 orders can cause 101 statements. The problem is repeated round trips and work, not merely the number 101. Do not globally change everything to EAGER. Ask what this endpoint needs and select that graph deliberately. SQL logging, Hibernate statistics, or integration tests can prove whether the change actually removed the repeated queries.
Hibernate N+1 Query Problem
Direct Answer
The N+1 problem means one query loads a list of N objects and later access causes up to N additional queries for related data. Lazy access is a common cause, but an eager mapping can also produce secondary selects, so lazy loading is not the definition. Fix the query for the use case with a fetch join, entity graph, projection, or batching, and verify the SQL.
Common Mistakes & Pitfalls
- Not detecting it — testing with 2-3 rows and never enabling SQL logging, so the query flood goes unnoticed. Always turn on
spring.jpa.show-sql=truein development. - Going EAGER globally — switching
@OneToMany(fetch = EAGER)to dodge N+1 means you always load children even when unneeded. Use JOIN FETCH selectively per query instead. - Lazy access outside the transaction — touching a lazy collection after the transaction closes throws
LazyInitializationException; the fix is fetching it in the query, not making everything EAGER.
Check your understanding
Answer these without looking back at the article.
- How do you detect the N+1 problem in Spring Boot?
- What is @EntityGraph?
- What is the difference between EAGER and LAZY loading and how does it relate to N+1?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.