One of the most asked Java/backend interview questions in an interview
โThe N 1 Problem in JPA
โ 1 initial query: To fetch N parent entities.
โ N subsequent queries: For each of the N parent entities, a separate query is executed to fetch its related children.
โ Results in 1 N database queries, causing inefficiency and slow response, performance issue
Eg: Fetching 100 Authors(1 query) and then, in a loop, getting author.getBooks() for each(N=100), leads to 101 queries.
โHow to Resolve N 1 in JPA
โ Goal is to fetch associated data in fewer queries, usually in a single round trip.
โJPQL/HQL JOIN FETCH (Recommended for specific joins):
Explicitly tells JPA to fetch associations using a JOIN in your query.
Eg:
@Query("SELECT a FROM Author a JOIN FETCH a.books")
List<Author> findAllWithBooks();
Benefit: Single, efficient query.
Caution: Can lead to Cartesian products if joining multiple collections.
โBatch Fetching (
@BatchSize or hibernate.default_batch_fetch_size):
Instead of one query per parent, fetches associated collections for a batch of parent IDs in a single query.
Eg:
@BatchSize(size = 10)
@OneToMany(...)
private List<Book> books;
Benefit: Reduces 1 N to 1 (N / batch_size) queries, avoiding Cartesian products.
โEntity Graphs (@EntityGraph - Spring Data JPA / JPA 2.1 ):
Declaratively defines which associations to fetch eagerly for a specific repository method.
Eg:
@EntityGraph(attributePaths = "books")
List<Author> findAll();
Benefit: Flexible, reusable fetching strategies without explicit JPQL joins.
Conclusion: Always use explicit fetching strategies (like JOIN FETCH,
@BatchSize, or EntityGraph) to address N 1 issues and ensure efficient database interaction
ALT N 1 Problem