Tutorial MAR 12, 2025 • 03 MIN READ

N+1 QUERY
PROBLEM

Abstract technical background

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:

ORDER.java JAVA
@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:

EXAMPLE.LOG TEXT
| 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:

READ BEYOND THE VOID

Technical blueprint background
Backend Notes

Reverse Proxy + Load Balancer + API Gateway

They are all middle layers. But they exist for very different reasons...

Read Entry
Abstract digital network
Backend Notes

Difference between SSL, TLS, and HTTPS

I honestly thought SSL, TLS, and HTTPS were just different names for the same thing but...

Read Entry
Circuit board macro
Backend Notes

Spring Boot ISO8583 Server using Jpos

Create ISO8583 Server in Springboot...

Read Entry