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();
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)