0
0
SpringbootDebug / FixIntermediate · 4 min read

How to Fix N+1 Problem in Spring Boot Efficiently

The N+1 problem in Spring Boot happens when fetching a list of entities causes extra queries for each related entity. Fix it by using @EntityGraph or JOIN FETCH in your JPA queries to load related data in one query.
🔍

Why This Happens

The N+1 problem occurs when your code loads a list of entities, and then for each entity, it separately loads related entities. This causes one query to get the main list (1), plus one query per item (+N each), leading to many database calls and slow performance.

java
public interface BookRepository extends JpaRepository<Book, Long> {
    List<Book> findAll();
}

// Service code
List<Book> books = bookRepository.findAll();
for (Book book : books) {
    System.out.println(book.getAuthor().getName());
}
Output
Hibernate: select * from book Hibernate: select * from author where id = ? Hibernate: select * from author where id = ? ... (one query per book's author)
🔧

The Fix

Use JOIN FETCH in your query or @EntityGraph annotation to tell JPA to load related entities together in one query. This reduces the number of queries from N+1 to just 1.

java
public interface BookRepository extends JpaRepository<Book, Long> {
    @Query("SELECT b FROM Book b JOIN FETCH b.author")
    List<Book> findAllWithAuthors();
}

// Service code
List<Book> books = bookRepository.findAllWithAuthors();
for (Book book : books) {
    System.out.println(book.getAuthor().getName());
}
Output
Hibernate: select b.*, a.* from book b join author a on b.author_id = a.id Author names printed without extra queries
🛡️

Prevention

Always plan your data fetching strategy to avoid lazy loading surprises. Use @EntityGraph or JOIN FETCH for known relationships you need. Enable SQL logging during development to spot N+1 queries early. Consider DTO projections to fetch only needed data.

⚠️

Related Errors

Similar issues include LazyInitializationException when accessing lazy-loaded data outside a transaction, and Cartesian product problems when using multiple joins incorrectly. Fix these by managing transactions properly and carefully designing fetch joins.

Key Takeaways

The N+1 problem causes many extra database queries and slows your app.
Use JOIN FETCH or @EntityGraph to load related entities in one query.
Enable SQL logging to detect N+1 queries during development.
Plan your data fetching strategy to avoid lazy loading surprises.
Consider DTO projections for efficient data retrieval.