The N+1 problem is a common performance issue in Hibernate/JPA that occurs when the application executes one query to fetch the main entity and then N additional queries to fetch related data.
👉 This leads to too many database queries, slowing down the application.
Why is it Called N+1?
- 1 query → Fetch parent data
- N queries → Fetch related data for each record
👉 Total = N + 1 queries
Example Scenario
Consider two entities:
User-
Order(OneToMany relationship)
Step 1: Fetch Users
SELECT * FROM users;
👉 Suppose it returns 5 users.
Step 2: Fetch Orders (Lazy Loading)
For each user, Hibernate executes:
SELECT * FROM orders WHERE user_id = 1;
SELECT * FROM orders WHERE user_id = 2;
SELECT * FROM orders WHERE user_id = 3;
SELECT * FROM orders WHERE user_id = 4;
SELECT * FROM orders WHERE user_id = 5;
👉 Total queries = 1 (users) + 5 (orders) = 6 queries
This is the N+1 problem.
Why N+1 is a Problem
- Too many database calls
- Increased response time
- Poor performance
- Not scalable for large data
When Does It Occur?
- Mostly with Lazy Loading
- When accessing related collections inside loops
How to Solve N+1 Problem
1. Use JOIN FETCH
java id="v8a4ur"
@Query("SELECT u FROM User u JOIN FETCH u.orders")
List getUsersWithOrders();
👉 Fetches everything in one query.
2. Use Entity Graph
java id="zrs7aw"
@EntityGraph(attributePaths = {"orders"})
List findAll();
3. Use Batch Fetching
properties
hibernate.default_batch_fetch_size=10
4. Use DTO Projections
Fetch only required data instead of full entities.
Lazy vs Eager and N+1
- Lazy Loading → Can cause N+1 if not handled properly
- Eager Loading → Avoids N+1 but may load unnecessary data
👉 Best practice is to use optimized queries (JOIN FETCH).
Conclusion
The N+1 problem is a critical performance issue in Hibernate where multiple unnecessary queries are executed. Understanding and fixing it using techniques like JOIN FETCH, EntityGraph, or batching is essential for building efficient applications.
🚀 Learn Java & Backend Optimization
Master advanced concepts with Best Core JAVA Online Training.
Top comments (0)