Introduction
Java applications that use JPA and Hibernate often handle complex object relationships, such as one-to-many and many-to-one mappings. One of the most critical decisions developers make is choosing between lazy loading and eager loading. While both options functionally work, they have a significant impact on application performance, database load, memory usage, and scalability. This article explains JPA lazy and eager loading in simple words, compares their performance impact, and helps you decide when to use each approach in real-world Java applications.
What Is Fetching in JPA?
Fetching refers to how related entities are loaded from the database when a parent entity is retrieved. JPA provides two fetch strategies:
Lazy loading
Eager loading
The fetch strategy controls when associated data is loaded, not what data exists.
Lazy Loading Explained
Lazy loading means related entities are not loaded immediately. They are fetched only when they are actually accessed in code.
Example: Lazy Loading Mapping
@Entity
public class Order {
@Id
private Long id;
@OneToMany(mappedBy = "order", fetch = FetchType.LAZY)
private List<OrderItem> items;
}
In this case, OrderItem data is not loaded until getItems() is called.
How Lazy Loading Works Internally
Hibernate creates a proxy object instead of loading the actual data. When the proxy is accessed, an additional SQL query is triggered.
This behavior helps reduce unnecessary data loading but can also introduce performance issues if not handled carefully.
Performance Benefits of Lazy Loading
Lazy loading improves performance by:
Reducing initial query size
Lowering memory usage
Loading only required data
Improving response time for simple queries
Lazy loading is especially useful in large enterprise systems with complex object graphs.
Common Problems with Lazy Loading
N+1 Query Problem
One of the biggest issues with lazy loading is the N+1 query problem.
Example Scenario
List<Order> orders = orderRepository.findAll();
for (Order order : orders) {
System.out.println(order.getItems().size());
}
This results in:
1 query to fetch orders
N additional queries to fetch items for each order
This can severely degrade performance.
Eager Loading Explained
Eager loading means related entities are loaded immediately along with the parent entity.
Example: Eager Loading Mapping
@Entity
public class Order {
@Id
private Long id;
@OneToMany(mappedBy = "order", fetch = FetchType.EAGER)
private List<OrderItem> items;
}
Here, Order and OrderItem are loaded in a single query or join.
Join the conversation! Your thoughts help the community grow.