BBackend CourseLeroy Labs
0/0
Search the course

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.

● intermediateSpring-Boot-StoreHostel-Web-AppReport-Manager-2IR3D (Kontentt)

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

Spring-Boot-Storerepositories/OrderRepository.java · CartRepository · UserRepository

Store uses @EntityGraph everywhere: OrderRepository fetches {"items.product"}, CartRepository.findCartWithItems loads the items, and UserRepository.findAll is overridden with {"addresses", "wishlist", "profile"}.

Hostel-Web-Appmodule/booking/repository/BookingRepository.java · RoomRepository.java

JPQL 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.

Report-Manager-22 x @EntityGraph · custom ReportHistoryRepositoryImpl

RM 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.

IR3D (Kontentt)5 x @EntityGraph · AdminDashboardQueryRepository

Dedicated 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
  • 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 visible LazyInitializationExceptions, 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-proxy or Hypersistence’s SQLStatementCountValidator can assert “this endpoint runs ≤ 3 queries”.

Check yourself

1. You list 100 bookings and print each room number. Lazy @ManyToOne, no fetch plan. How many queries (no cache)?
2. Why is JOIN FETCH on a collection + paging risky?