Why interviewers ask this: it shows whether you can spot a hidden database bottleneck before it becomes a production slowdown.
Question: Explain the N+1 query problem in Spring Boot with Spring Data JPA.
Answer: The N+1 query problem happens when your app loads one list of parent rows with one SQL query, then runs one extra query for each parent row when you touch a lazy relationship such as a collection. So if I load 50 authors and then read each author’s books, I may execute 51 queries instead of 1. In Spring Data JPA, this usually appears with `@OneToMany` or `@ManyToOne` mappings and is fixed by changing the fetch plan, not by adding more Java code.
Interview-Ready Answer: I’d say the N+1 query problem is when I fetch one set of entities with one query, but then Hibernate fires one additional query per entity as soon as I access a lazy association. In Spring Boot, I usually solve it with a fetch join, an `@EntityGraph`, or batch fetching, depending on whether I need pagination and how much data I’m loading. The key point is that the cost is not the loop in Java — it is the extra database round trips.
Detailed Explanation: N+1 is query amplification: one query to load the parents, then N more queries to load children one parent at a time. Hibernate does this most often with lazy loading, where a relation is fetched only when you touch it.
| Approach | Queries | Good for | Caveat |
|---|---|---|---|
| Lazy access + loop | 1 + N | Very small data | Hidden round trips |
| Fetch join | Usually 1 | Read-heavy screens | Duplicates, pagination issues |
| `@EntityGraph` | 1 or a few | Declarative fetch plans | Provider behavior matters |
| Batch fetching | 1 + ceil(N/B) | Large lists | Still more than one query |
For many Spring Boot apps, the best default is to keep relations lazy and fetch them explicitly on the query that needs them. A fetch join is often the cleanest option when you know exactly which graph you need. If the list is large or pagination matters, batch fetching with a size like 16 or 32 can reduce the damage without exploding the result set.
The time cost is mostly network and database round trips, so the problem grows with latency. A page with 80 parents can become 81 queries; at only 5 ms of extra round-trip time each, that is roughly 400 ms of extra delay before you count database work. Query count is the big-O story here: naive access is O(N) queries, while batch fetching becomes roughly O(N / B), where B is the batch size. Space use also rises because Hibernate must keep more managed entities in memory, and fetch joins can duplicate parent rows in the SQL result set.
Memory model: think of it as one shopping cart and N extra warehouse trips: the cart load is cheap, but every time you reach for a new item, the warehouse gets another call.
Real-World Example: In an e-commerce admin service, an `Order` page showed each order with its line items. A developer added `order.getItems().size()` inside a loop to display counts, and the endpoint went from a few SQL statements to hundreds. In production, the symptom was slow page loads, a noisy log full of repeated `select ... where order_id = ?` statements, and connection pool pressure during peak traffic. Users saw timeouts, and the fix was to replace the naive loop with a fetch join for that screen plus a DTO so the controller only received the fields it needed.
package com.example.nplusone;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.LazyInitializationException;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class NPlusOneDemoApplication {
public static void main(String[] args) {
SpringApplication.run(NPlusOneDemoApplication.class, args);
}
@Bean
CommandLineRunner runner(AuthorRepository authorRepository, DemoService demoService) {
return args -> {
authorRepository.deleteAll();
seed(authorRepository);
demoService.showLazyInitializationFailure();
demoService.showNPlusOne();
demoService.showFetchJoin();
};
}
private void seed(AuthorRepository repo) {
Author alice = new Author("Alice");
alice.addBook(new Book("Spring in Action"));
alice.addBook(new Book("JPA Mastery"));
Author bob = new Author("Bob");
bob.addBook(new Book("Hibernate Tips"));
Author cara = new Author("Cara"); // Edge case: a parent with no children still participates in the query.
repo.saveAll(List.of(alice, bob, cara));
}
}
// File: src/main/java/com/example/nplusone/Author.java
package com.example.nplusone;
import java.util.ArrayList;
import java.util.List;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// Lazy keeps the initial query small; touching the collection later can trigger the N in N+1.
@OneToMany(mappedBy = "author", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private List<Book> books = new ArrayList<>();
protected Author() {
}
public Author(String name) {
this.name = name;
}
public void addBook(Book book) {
books.add(book);
book.setAuthor(this);
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public List<Book> getBooks() {
return books;
}
}
// File: src/main/java/com/example/nplusone/Book.java
package com.example.nplusone;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "author_id")
private Author author;
protected Book() {
}
public Book(String title) {
this.title = title;
}
public Long getId() {
return id;
}
public String getTitle() {
return title;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
}
// File: src/main/java/com/example/nplusone/AuthorRepository.java
package com.example.nplusone;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
public interface AuthorRepository extends JpaRepository<Author, Long> {
// DISTINCT removes duplicate Author objects caused by joining to many Book rows.
@Query("select distinct a from Author a left join fetch a.books")
List<Author> findAllWithBooks();
}
// File: src/main/java/com/example/nplusone/DemoService.java
package com.example.nplusone;
import java.util.List;
import org.hibernate.LazyInitializationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class DemoService {
private final AuthorRepository authorRepository;
public DemoService(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
public void showLazyInitializationFailure() {
System.out.println("\n--- LazyInitializationException demo ---");
List<Author> authors = authorRepository.findAll();
try {
// Outside a transaction, the lazy collection has no open session to load itself.
System.out.println("First author's books: " + authors.get(0).getBooks().size());
} catch (LazyInitializationException ex) {
System.out.println("Expected failure: " + ex.getClass().getSimpleName() + " - " + ex.getMessage());
}
}
@Transactional(readOnly = true)
public void showNPlusOne() {
System.out.println("\n--- N+1 demo ---");
List<Author> authors = authorRepository.findAll();
int totalBooks = 0;
for (Author author : authors) {
// Each access can trigger one SELECT per author when the collection is still lazy.
int count = author.getBooks().size();
totalBooks += count;
System.out.println(author.getName() + " -> " + count + " books");
}
System.out.println("Total books = " + totalBooks);
}
@Transactional(readOnly = true)
public void showFetchJoin() {
System.out.println("\n--- Fetch join demo ---");
List<Author> authors = authorRepository.findAllWithBooks();
int totalBooks = 0;
for (Author author : authors) {
// Books are already loaded by the join, so this loop does not fan out into extra queries.
int count = author.getBooks().size();
totalBooks += count;
System.out.println(author.getName() + " -> " + count + " books");
}
System.out.println("Total books = " + totalBooks);
}
}
// File: src/main/resources/application.properties
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;MODE=PostgreSQL
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
logging.level.org.hibernate.SQL=DEBUGFollow-up & Tricky Questions:
Common Mistakes:
Memory Hook: One shopping cart, many warehouse trips. Load the cart once, but every extra lazy lookup is another trip to the warehouse.
Cheat Sheet:
Practice Tasks: