Difference Between EAGER and LAZY Loading in JPA
EAGER Loading and LAZY Loading are fetch strategies in JPA and Hibernate used to control how related entities are loaded from the database.
These fetch strategies directly impact:
- Application performance
- Memory usage
- Database query execution
- Scalability
In simple words:
- EAGER Loading → Load related data immediately
- LAZY Loading → Load related data only when needed
Why Fetch Strategies are Important
Enterprise applications often contain relationships such as:
- Customer → Orders
- Student → Courses
- User → Roles
Loading all related data unnecessarily can:
- Reduce performance
- Increase memory usage
- Create slow database queries
Fetch strategies help optimize these operations.
What is EAGER Loading?
In EAGER loading, related entities are loaded immediately along with the parent entity.
EAGER Loading Example
@ManyToOne(fetch = FetchType.EAGER)
private Department department;
How EAGER Loading Works
Suppose:
- Employee belongs to Department
When Employee is fetched:
- Department is also fetched automatically
EAGER Loading Flow
Load Employee
↓
Automatically Load Department
Generated SQL Example for EAGER Loading
SELECT e.*, d.*
FROM employees e
LEFT JOIN departments d
ON e.department_id = d.id
Advantages of EAGER Loading
- Related data available immediately
- No additional query required later
- Simpler object access
Disadvantages of EAGER Loading
- Can reduce performance
- Loads unnecessary data
- Higher memory usage
- Large JOIN queries
What is LAZY Loading?
In LAZY loading, related entities are loaded only when accessed explicitly.
LAZY Loading Example
@OneToMany(fetch = FetchType.LAZY)
private List<Order> orders;
How LAZY Loading Works
Suppose:
- Customer has many orders
When Customer is fetched:
- Orders are NOT loaded immediately
- Orders load only when getOrders() is called
LAZY Loading Flow
Load Customer
↓
Orders NOT Loaded
↓
Call getOrders()
↓
Orders Loaded
Generated SQL Example for LAZY Loading
Initial Query
SELECT *
FROM customers
WHERE id = 1
Later Query
SELECT *
FROM orders
WHERE customer_id = 1
Advantages of LAZY Loading
- Better performance
- Lower memory usage
- Loads data only when required
- Efficient for large collections
Disadvantages of LAZY Loading
- Additional queries may occur
- Can cause LazyInitializationException
- More debugging complexity
Main Difference Between EAGER and LAZY Loading
| Feature | EAGER Loading | LAZY Loading |
|---|---|---|
| Loading Time | Immediately | On demand |
| Performance | Can be slower | Usually faster |
| Memory Usage | Higher | Lower |
| Database Queries | Fewer but larger | More but smaller |
| Complexity | Simpler | More complex |
Default Fetch Types in JPA
| Relationship | Default Fetch Type |
|---|---|
| @OneToOne | EAGER |
| @ManyToOne | EAGER |
| @OneToMany | LAZY |
| @ManyToMany | LAZY |
Real-Time Example in E-Commerce Application
Suppose:
- One customer has 10,000 orders
If EAGER loading is used:
- All orders load immediately
- Application becomes slower
If LAZY loading is used:
- Orders load only when needed
- Performance improves
Entity Example Using EAGER Loading
@Entity
public class Employee {
@Id
private Long id;
@ManyToOne(fetch = FetchType.EAGER)
private Department department;
}
Entity Example Using LAZY Loading
@Entity
public class Customer {
@Id
private Long id;
@OneToMany(
mappedBy = "customer",
fetch = FetchType.LAZY
)
private List<Order> orders;
}
What is LazyInitializationException?
This exception occurs when:
- LAZY-loaded data is accessed
- After Hibernate session is closed
Example Error
failed to lazily initialize a collection
Why LazyInitializationException Happens
Hibernate session closes before:
getOrders()
is called.
Solutions for LazyInitializationException
- Use JOIN FETCH queries
- Use transactional methods
- Use DTO projections
- Use Open Session in View carefully
JOIN FETCH Example
@Query("""
SELECT c
FROM Customer c
JOIN FETCH c.orders
WHERE c.id = :id
""")
Customer findCustomerWithOrders(Long id);
What is N+1 Query Problem?
N+1 problem occurs when:
- One query fetches parent entities
- Additional queries repeatedly fetch child entities
N+1 Example
List<Customer> customers =
customerRepository.findAll();
for (Customer customer : customers) {
customer.getOrders();
}
When to Use EAGER Loading
- Small relationships
- Always-needed related data
- Critical parent-child access
When to Use LAZY Loading
- Large collections
- Performance-sensitive applications
- REST APIs
- Microservices
Best Practices for Fetch Strategies
- Prefer LAZY loading for collections
- Avoid excessive EAGER loading
- Use DTOs for APIs
- Optimize JOIN queries
- Monitor generated SQL queries
Advantages of Proper Fetch Strategy
- Improved performance
- Better scalability
- Reduced memory usage
- Optimized database queries
Disadvantages of Improper Fetch Strategy
- Slow application performance
- Memory issues
- Too many database queries
- N+1 query problems
Real-Time Example in Banking Application
Banking application contains:
- Customer
- Transactions
One customer may have:
- Millions of transactions
Loading all transactions immediately using EAGER loading can severely reduce performance.
LAZY loading is usually preferred in such systems.
Common Interview Questions on EAGER and LAZY Loading
What is EAGER loading?
EAGER loading fetches related entities immediately.
What is LAZY loading?
LAZY loading fetches related entities only when needed.
Which fetch type is better?
LAZY loading is usually preferred for better performance.
What is the default fetch type for @OneToMany?
LAZY.
What is LazyInitializationException?
It occurs when LAZY-loaded data is accessed outside Hibernate session.
Conclusion
EAGER and LAZY loading are very important fetch strategies in JPA and Hibernate.
They control:
- How related entities load
- Database query execution
- Application performance
Choosing the correct fetch strategy is critical for building scalable, optimized, and high-performance Spring Boot applications.
Most enterprise applications prefer:
- LAZY loading for collections
- EAGER loading only when necessary
Understanding the difference between EAGER and LAZY loading is essential for every Spring Boot and Hibernate developer.