Video in progress
What's the difference between lazy and eager loading?
With eager, the related object is loaded right away together with the main entity. With lazy, a proxy or an empty collection wrapper is put in its place, and the data is read only the first time you access it.
📖 Answer
The difference is when the data is read. Take a simple order example:
@Entity
public class Order {
@ManyToOne(fetch = FetchType.LAZY)
private Customer customer;
@OneToMany(mappedBy = "order") // default LAZY
private List<OrderItem> items;
}
Order o = em.find(Order.class, 1L); // only the orders table
o.getCustomer().getName(); // SELECT on customers here
o.getItems().size(); // SELECT on order_items here
If you never need the lazy data, it isn't read. Eager always reads it, even when all you need is the order number.
The rule in practice is simple: make every association LAZY, and where you need the data, load it with an explicit query using JOIN FETCH or an entity graph. So the decision of "what gets loaded" is made per use case, not in the mapping.
The price of lazy is LazyInitializationException when you access data outside a transaction, and N+1 if you use it carelessly.
Sign up to mark studied questions and save your progress.