DEV Community

Shubham Bhati
Shubham Bhati

Posted on

Crush N+1 Queries for Faster APIs

Ever seen an API that should be fast but isn't? Check your database interactions. A common culprit is the N+1 query problem, especially with lazy-loaded collections in JPA. You load one parent entity, then N separate queries fire to fetch each of its child collections. Massive overhead.

Imagine loading 100 Order entities, each with a lazy List<OrderItem>. That's 101 database queries for a single API call! Ouch.

The fix is often simple: tell JPA to fetch related entities in one go. Use JOIN FETCH in your Spring Data JPA repository methods.

public interface OrderRepository extends JpaRepository<Order, Long> {
    @Query("SELECT o FROM Order o JOIN FETCH o.items WHERE o.id = :orderId")
    Optional<Order> findByIdWithItems(@Param("orderId") Long orderId);

    // Or for all orders with items:
    @Query("SELECT DISTINCT o FROM Order o JOIN FETCH o.items")
    List<Order> findAllWithItems();
}
Enter fullscreen mode Exit fullscreen mode

This transforms N+1 queries into a single, efficient join. Your database will thank you and your API performance will soar. Don't let lazy loading make your APIs lazy.

Top comments (0)