Spring / Spring7 Intermediate to Advanced Interview questions
How do you optimize a Spring Data JPA application to avoid the N+1 query problem?
The N+1 problem shows up when loading a list of parent entities triggers one query for the list, then a separate lazy-loading query for each row's related association - a hundred orders each lazily fetching their line items means a hundred and one round trips to the database instead of two.
@Query("SELECT o FROM Order o JOIN FETCH o.lineItems WHERE o.status = :status") List<Order> findByStatusWithItems(@Param("status") String status); // or, without changing the entity's default fetch type globally @EntityGraph(attributePaths = "lineItems") List<Order> findByStatus(String status);
JOIN FETCH in a JPQL query eagerly pulls the association into the same single query. @EntityGraph achieves the same result for a specific repository method without changing the entity's default (and normally sensible) lazy-fetch type everywhere else. For associations that can't cleanly be joined - a collection accessed across many different code paths - Hibernate's batch fetching (hibernate.default_batch_fetch_size, or @BatchSize on the association) groups the lazy loads into batched IN (...) queries instead of one row at a time, which is a lower-effort fix when a targeted JOIN FETCH isn't practical. Finally, when the use case only needs a handful of fields, a Spring Data projection or DTO query avoids hydrating full entity graphs at all, sidestepping the N+1 question entirely for read-heavy endpoints.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
