What is the N+1 problem in JPA and how do you fix it?
Options
- It means the database has N+1 tables in its schema
- One query for N parents, then one per parent:
JOIN FETCH(Correct option) - It means the application uses N+1 threads in total
- It is a syntax error that JPQL reports at startup
Answer
One query loads N parents, then one extra query per parent loads its children (N+1 queries total). Fix with JOIN FETCH, @EntityGraph or batch fetching
Why
Example: findAll() loads 100 users (1 query). Then your code loops and calls user.getOrders(), which is LAZY, so JPA runs 1 query per user: 100 more. Total 101 queries instead of 1 or 2.
Fixes: select u from User u join fetch u.orders loads everything with one JOIN; @EntityGraph(attributePaths = "orders") on the repository method; @BatchSize to load children in groups; or a DTO projection that selects only what you need.
Detect it by turning on SQL logging and counting queries.
@Query("select u from User u join fetch u.orders")
List<User> findAllWithOrders();Remember
N+1 = 1 query for parents + 1 per child. Fetch join solves it.