N+1 QUERY
PROBLEM
The N+1 query problem occurs because of how ORM frameworks such as Hibernate ORM (used by Spring Boot through Spring Data JPA) load entity relationships.
Case Discussion
Assume the typical mapping:
@Entity
class Order {
@OneToMany(mappedBy = "order", fetch = FetchType.LAZY)
private List<OrderItem> items;
}Step-by-step execution of your code:
List<Order> orders = orderRepository.findAll();
The ORM executes one SQL query:
SELECT * FROM orders;
Suppose this returns N orders.
Example result:
| order_id |
| -------- |
| 1 |
| 2 |
| 3 |At this point items are not loaded yet because the relationship uses LAZY loading.
Then your code accesses:
order.getItems()
For each order, Hibernate must load the associated items. Because they were not fetched earlier, it executes one additional query per order:
SELECT * FROM order_items WHERE order_id = 1;
SELECT * FROM order_items WHERE order_id = 2;
SELECT * FROM order_items WHERE order_id = 3;
Total queries executed:
1 query -> load orders
N queries -> load items for each order
-------------------------------
N + 1 queries
Example with 100 orders:
1 query -> SELECT orders
100 queries -> SELECT items by order_id
--------------------------------------
101 queries total
This is inefficient because:
- check_circle Many round trips to the database
- check_circle Increased latency
- check_circle Poor scalability under load
Why the ORM behaves this way:
- check_circle @OneToMany defaults to LAZY fetching
- check_circle The ORM loads relations only when accessed
- check_circle Accessing the collection triggers a separate query
Typical ways to solve it: