Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is the N+1 query problem and how do you solve it in Spring Data JPA? N+1 क्वेरी समस्या क्या है और स्प्रिंग डेटा JPA में इसे कैसे हल करें?

Answer

The N+1 problem occurs when fetching a list of N parent entities triggers 1 query for the parents plus N additional queries, one per parent, to lazily load each one's related collection or association — resulting in N+1 total queries instead of one efficient join.

It's solved by fetching related data eagerly in a single query using JOIN FETCH in a JPQL query, an @EntityGraph on the repository method to specify which associations to load together, or by batching lazy fetches with @BatchSize to reduce the number of round-trips.

@Query("SELECT a FROM Author a JOIN FETCH a.books")
List<Author> findAllWithBooks();

@EntityGraph(attributePaths = "books")
List<Author> findAll();

N+1 समस्या तब होती है जब N पैरेंट एंटिटीज़ की लिस्ट फेच करने से पैरेंट्स के लिए 1 क्वेरी और हर पैरेंट के संबंधित कलेक्शन को लेज़ी लोड करने के लिए N अतिरिक्त क्वेरीज़ ट्रिगर होती हैं — कुल N+1 क्वेरीज़, जबकि एक कुशल जॉइन से यह काम हो सकता था।

इसे हल करने के लिए JPQL क्वेरी में JOIN FETCH का उपयोग करके एक ही क्वेरी में संबंधित डेटा ईगरली फेच किया जाता है, रिपॉज़िटरी मेथड पर @EntityGraph लगाया जाता है, या @BatchSize से लेज़ी फेच को बैच किया जाता है।

@Query("SELECT a FROM Author a JOIN FETCH a.books")
List<Author> findAllWithBooks();

@EntityGraph(attributePaths = "books")
List<Author> findAll();

Was this answer clear?