You know that dreaded N+1 query problem, right? When you fetch a list of Orders and then lazily load each Customer inside a loop? That's your database taking a hit, turning one query into N+1 for N orders. Performance tanks, especially under load.
Instead of letting JPA make a separate query for every associated entity, explicitly tell it to fetch everything at once. Use a FETCH JOIN in your JPQL or leverage an @EntityGraph. It's a simple change with a massive performance win.
// Avoid N+1 for customer details
@Query("SELECT o FROM Order o JOIN FETCH o.customer")
List<Order> findAllOrdersWithCustomers();
This single query now retrieves all Order and Customer data in one go. Less round trips to the database, faster responses. Always profile your queries and watch that network tab.
Top comments (0)