DEV Community

Shubham Bhati
Shubham Bhati

Posted on

Beat the N+1 Query Beast in Spring Boot

You've got an API fetching a list of parent entities and for each parent you need to display some child data. The common mistake is to let Spring Data JPA fetch the parent list then lazily load children in a loop triggering N+1 queries. That's a performance killer.

Instead of List<Parent> findAll(); use a dedicated query to fetch everything upfront.

@Query("SELECT p FROM Parent p JOIN FETCH p.children")
List<Parent> findAllWithChildren();
Enter fullscreen mode Exit fullscreen mode

This single SELECT query grabs all parents and their associated children in one shot hydrating your entities properly. For read-heavy operations especially when exposing nested data via DTOs this is a game-changer. Avoids multiple database round trips keeping your API fast and your database happy.

Top comments (0)