Difficulty: Advanced
Your endpoint that lists departments with their employees suddenly generates hundreds of SQL queries. What is happening and how do you fix it?
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.
@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.
N+1 Problem, OneToMany, Join Fetch, EntityGraph