# JPA Relationships and the N+1 Query Problem

> Your endpoint that lists departments with their employees suddenly generates hundreds of SQL queries. What is happening and how do you fix it?

Canonical: https://www.internhack.in/learn/interview/spring-boot-interview/spring-jpa-relationships-n-plus-one
Last updated: 2026-11-28

Difficulty: Advanced

## Question

Your endpoint that lists departments with their employees suddenly generates hundreds of SQL queries. What is happening and how do you fix it?

## Answer

This is one of the most realistic production performance problems in Spring Boot, and if you describe it well you will stand out. It is called the N+1 select problem, and it hides quietly in development with five rows of test data and explodes in production with five thousand.

First the relationship basics. @OneToMany and @ManyToOne model the classic parent-child link, like one Department with many Employees. The owning side is the one holding the foreign key, the many side, so Employee has @ManyToOne Department department and Department has @OneToMany(mappedBy = "department") List<Employee> employees. The mappedBy attribute says the other side owns the join column. @ManyToMany uses a join table, and @OneToOne links one to one. Cascade settings such as CascadeType.ALL and orphanRemoval control whether operations propagate to children.

Now the problem. By default, collections are lazy. When you call departmentRepository.findAll(), Hibernate runs one query to get N departments. Then, as your code or Jackson serialisation touches department.getEmployees() for each one, Hibernate fires a separate select for each department's employees. That is 1 query for the parents plus N queries for the children, hence N+1. With 500 departments you make 501 round trips to the database. The same thing happens for @ManyToOne when it is eager: findAll on employees loads each employee's department individually. Think of it as asking a librarian for a list of authors and then walking back separately for each author's books instead of asking for everything at once.

How do you detect it? Enable SQL logging with spring.jpa.show-sql or logging.level.org.hibernate.SQL=DEBUG, and set spring.jpa.properties.hibernate.generate_statistics=true to see query counts. Tools like Hibernate statistics, datasource-proxy, or p6spy show repeated selects. In tests you can assert the query count.

Fixes, in order of preference. First, a fetch join in JPQL: select d from Department d left join fetch d.employees loads everything in one query. Watch out for duplicates on collection joins, so use distinct, and know that you cannot combine join fetch of a collection with pagination cleanly, since Hibernate then paginates in memory and warns HHH000104. Second, @EntityGraph on a repository method, which declares which associations to load without writing JPQL. Third, batch fetching: set spring.jpa.properties.hibernate.default_batch_fetch_size=50 or @BatchSize, which turns N queries into roughly N over 50 by loading children with IN clauses. This works well with pagination. Fourth, use a DTO projection selecting only the columns you need, avoiding entity graphs altogether, which is often the best approach for read-heavy list endpoints.

What not to do: do not switch everything to FetchType.EAGER. That makes the problem worse and unpredictable because the fetch happens whether you need the data or not. Also avoid returning entities from controllers, because Jackson will traverse lazy relations and trigger the queries, or throw LazyInitializationException and loop infinitely on bidirectional references.

## Code examples

### The problem and three fixes

```
@Entity
class Department {
    @Id @GeneratedValue Long id;
    String name;

    @OneToMany(mappedBy = "department", cascade = CascadeType.ALL, orphanRemoval = true)
    List<Employee> employees = new ArrayList<>();
}

@Entity
class Employee {
    @Id @GeneratedValue Long id;
    String name;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "department_id")
    Department department;
}

interface DepartmentRepository extends JpaRepository<Department, Long> {

    List<Department> findAll();                                        // N+1 when employees touched

    @Query("select distinct d from Department d left join fetch d.employees")
    List<Department> findAllWithEmployees();                           // fix 1: fetch join

    @EntityGraph(attributePaths = "employees")
    List<Department> findByNameContaining(String name);                // fix 2: entity graph

    @Query("select new com.app.DeptSummary(d.name, count(e)) " +
           "from Department d left join d.employees e group by d.name")
    List<DeptSummary> summary();                                       // fix 3: DTO projection
}
```

Choose fetch join or entity graph when you need the entities, and a DTO projection when you only need a summary.

## Key points

- Owning side is the one with the foreign key; mappedBy is on the inverse side.
- Distinct is needed on collection join fetch to remove duplicate parents.
- Join fetch on a collection with pagination causes in-memory paging.
- default_batch_fetch_size is a cheap global mitigation.

## Common follow-up questions

- Why does join fetch plus pagination cause problems?
- How would you detect N+1 in an automated test?
- Difference between mappedBy and JoinColumn?

## Interview tips

- Describe symptom, detection, and fix, in that order.
- Warn against switching to EAGER; that shows depth.

## Concepts covered

N+1 Problem, OneToMany, Join Fetch, EntityGraph

Previous: [Spring Data JPA: Repositories, Derived Queries and @Query](https://www.internhack.in/learn/interview/spring-boot-interview/spring-data-jpa-repositories-queries) · Next: [Lazy vs Eager Fetching and LazyInitializationException](https://www.internhack.in/learn/interview/spring-boot-interview/spring-jpa-lazy-vs-eager-fetching) · [All of Spring Boot](https://www.internhack.in/learn/interview/spring-boot-interview)

## More Spring Boot questions

- [@Transactional: Propagation, Rollback Rules and Self-Invocation](https://www.internhack.in/learn/interview/spring-boot-interview/spring-transactional-pitfalls)
- [Hibernate First-Level and Second-Level Cache](https://www.internhack.in/learn/interview/spring-boot-interview/spring-hibernate-caching)
- [Spring Security Filter Chain and JWT Authentication Flow](https://www.internhack.in/learn/interview/spring-boot-interview/spring-security-filter-chain-jwt)
- [Password Encoding with BCrypt in Spring Security](https://www.internhack.in/learn/interview/spring-boot-interview/spring-security-password-encoding)
- [Spring Boot Actuator for Production Monitoring](https://www.internhack.in/learn/interview/spring-boot-interview/spring-boot-actuator)
- [Spring AOP: Aspects, Advice and Proxies](https://www.internhack.in/learn/interview/spring-boot-interview/spring-aop-basics)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Spring Boot](https://www.internhack.in/learn/interview/spring-boot-interview)
