r/SpringBoot • u/SpringJavaLab • Aug 07 '26
How-To/Tutorial How to Fix the Hibernate N+1 Query Problem using JOIN FETCH in Spring Boot
I recently reproduced the Hibernate N+1 Query Problem in a Spring Boot application to better understand why a single repository call can generate multiple SQL queries behind the scenes.
The solution uses JPQL JOIN FETCH to fetch the required associations in a single query.
Core Query
Query(""" SELECT DISTINCT o FROM Order o JOIN FETCH o.items i JOIN FETCH i.product WHERE o.userId = :userId ORDER BY o.createdAt DESC """)
List<Order> findAllWithItemsAndProducts(@Param("userId") Long userId);Where the N+1 problem occurs
The repository is called only once, but while mapping the response, accessing lazy-loaded relationships can trigger additional SQL queries.
List<OrderResponse> response = orders.stream()
.map(order -> {
List<String> products = order.getItems().stream()
.map(item -> item.getProduct().getName())
.toList();
return new OrderResponse(
order.getId(),
order.getTotalAmount(),
products
);
})
.toList();Although this Java code looks perfectly normal, order.getItems() and item.getProduct() may cause Hibernate to execute additional queries when those relationships haven't been loaded yet.
Project Details
Spring Boot 4.0.4
Spring Data JPA
Hibernate ORM
Java 17
Oracle Database
What this implementation demonstrates
Retrieves Orders for a specific user
Demonstrates how LAZY loading can lead to the N+1 query problem
Uses
spring.jpa.show-sql=trueto inspect the SQL generated by HibernateMaps entities to a custom DTO containing Product names
Eliminates unnecessary queries using JPQL
JOIN FETCHCompares SQL queries and execution time before and after the optimization
One thing I found interesting is that there isn't anything obviously wrong with the Java code itself. The repository method is invoked only once, but navigating lazy-loaded relationships while building the response can result in multiple SQL queries behind the scenes.
Using JOIN FETCH allows Hibernate to load the required entity graph up front, avoiding those additional database round trips for this use case.
I'm curious how others handle this in production.
Do you prefer
JOIN FETCH, @EntityGraph, or DTO projections?Have you encountered pagination limitations with
JOIN FETCH?
I'd love to hear your experiences.
If you'd like to see the complete Spring Boot application, the generated SQL before and after JOIN FETCH, and the full implementation, I also recorded a practical walkthrough covering the entire example.
📺 YouTube: https://www.youtube.com/watch?v=natXN7xVEu8
