Lazy loading, the N+1 problem, @EntityGraph & JOIN FETCH
The most common JPA performance bug. How to spot it in SQL logs and fix it with fetch joins, entity graphs, batch fetching or projections.
The concept
List<Order> orders = orderRepository.findByCustomer(user); // 1 query
for (Order o : orders)
for (OrderItem i : o.getItems()) // +1 query per order
i.getProduct().getName(); // +1 query per item (if not cached)
For 50 orders that is 1 + 50 + more queries. Each is fast on its own, but together they’re slow: round-trip latency multiplied by N. This is the N+1 problem.
Spot it
spring.jpa.show-sql: true # Store has this on
logging.level.org.hibernate.SQL: debug
logging.level.org.hibernate.orm.jdbc.bind: trace
If the same SELECT ... WHERE order_id=? appears 50 times, you have N+1.
Fixes
1. JOIN FETCH (JPQL)
@Query("SELECT b FROM Booking b JOIN FETCH b.room r JOIN FETCH r.hostel WHERE b.student.id = :sid")
List<Booking> findMineWithRoom(UUID sid);
2. @EntityGraph (declarative)
@EntityGraph(attributePaths = {"items.product"})
@Query("SELECT o FROM Order o WHERE o.customer = :customer")
List<Order> getOrdersByCustomer(User customer);
3. Batch fetching. @BatchSize(size = 50) or hibernate.default_batch_fetch_size=50 loads lazy children with WHERE id IN (...), 50 at a time. That turns N+1 into 1 + N/50.
4. DTO projection. Select only the columns you need into a record. No entities, no lazy loading.
In your projects
repositories/OrderRepository.java · CartRepository · UserRepositoryStore uses @EntityGraph everywhere: OrderRepository fetches {"items.product"}, CartRepository.findCartWithItems loads the items, and UserRepository.findAll is overridden with {"addresses", "wishlist", "profile"}.
module/booking/repository/BookingRepository.java · RoomRepository.javaJPQL JOIN FETCH, including combined with a lock: SELECT r FROM Room r JOIN FETCH r.hostel WHERE r.id = :id under PESSIMISTIC_WRITE loads the room and its hostel in one query and locks the room row.
2 x @EntityGraph · custom ReportHistoryRepositoryImplRM leans more on native queries and projections for its heavy reports (119 @Query methods). Report pages aggregate thousands of lines, so loading entities would be wasteful.
5 x @EntityGraph · AdminDashboardQueryRepositoryDedicated query repositories for the admin dashboards return aggregated DTOs directly. This is a mini read model.
Alternatives / complements
| Fix | Best for |
|---|---|
| JOIN FETCH | One-off queries with known needs |
| @EntityGraph | Reusing repository methods with different fetch plans |
| Batch size | A global safety net |
| DTO projections | Read-only lists and reports |
| Second-level cache | Rarely-changing reference data |
Related concepts you must know
open-in-view: false. All your projects disable it, so lazy loading can’t secretly happen during JSON rendering. That turns hidden N+1s into visibleLazyInitializationExceptions, which is a good thing (see the connection-pool lesson).- Cartesian products. Fetching two collections in one query multiplies the rows (10 items × 10 tags = 100 rows). Fetch one collection per query.
- Query counting in tests. Libraries like
datasource-proxyor Hypersistence’sSQLStatementCountValidatorcan assert “this endpoint runs ≤ 3 queries”.