wasAsked.

How do you identify and remove N+1 queries when using Hibernate and Spring Data JPA?

Flipkart · Full Stack Developer · 3-4-years · technical

Published

Year not specified · Java, Hibernate, JPA

Community answers

Posted by wasAsked editorial collection

The N+1 problem: one query loads N parent rows, then accessing a lazy association triggers one more query per row. List<Order> orders = orderRepository.findAll(); // 1 query orders.forEach(o -> o.getCustomer().getName()); // N queries for customers Identifying it - Enable SQL logging in development: spring.jpa.show-sql or logging.level.org.hibernate.SQL=DEBUG, and count queries per request. - Hibernate statistics (hibernate.generate_statistics=true) show query counts and entity loads. - Tools: datasource-proxy or p6spy to log and count statements; Hypersistence Utils' SQL statement count assertions in tests to fail builds when a request exceeds the expected number of queries. - APM tools (New Relic, Datadog, OpenTelemetry traces) reveal many similar queries per request in production. Fixing it 1. JOIN FETCH in JPQL: @Query("select o from Order o join fetch o.customer where o.status = :status") List<Order> findWithCustomer(@Param("status") Status status); 2. Entity graphs in Spring Data: @EntityGraph(attributePaths = {"customer", "items"}) List<Order> findByStatus(Status status); 3. DTO projections — often the best option for read APIs: @Query("select new com.shop.OrderSummary(o.id, c.name, o.total) from Order o join o.customer c") List<OrderSummary> summaries(); Interface-based and record projections also work, and they load only the needed columns. 4. Batch fetching: @BatchSize(size = 50) on associations or hibernate.default_batch_fetch_size=50 loads lazy associations for many parents in one IN query, reducing N+1 to roughly N/50+1 queries without changing the queries themselves. 5. @Fetch(FetchMode.SUBSELECT) for collections loaded for all parents at once. Pitfalls to mention - Do not switch associations to FetchType.EAGER globally: it causes unexpected joins and still produces N+1 in many JPQL queries. Keep associations LAZY (and explicitly mark @ManyToOne LAZY, since it defaults to EAGER) and fetch what each use case needs. - JOIN FETCH on several collections causes cartesian products, and Hibernate cannot fetch multiple bags (MultipleBagFetchException). Fetch collections in separate queries or use Sets carefully. - Pagination with collection fetch joins makes Hibernate paginate in memory (warning HHH90003004). Fetch IDs first with pagination, then fetch details for those IDs. - Disable open-in-view (spring.jpa.open-in-view=false) so lazy loading does not happen silently during JSON serialization.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics