Performance: Fetch types (LAZY vs EAGER)
This affects how and when related data is loaded from the database, impacting page load speed and responsiveness.
Jump into concepts and practice - no test required
class User {
@OneToMany(fetch = FetchType.LAZY)
Set<Order> orders;
}
// Orders load only when accessed explicitlyclass User {
@OneToMany(fetch = FetchType.EAGER)
Set<Order> orders;
}
// Fetching User loads all Orders immediately| Pattern | DB Queries | Memory Usage | Initial Load Time | Verdict |
|---|---|---|---|---|
| EAGER Fetch | Loads all related data immediately | High due to all data in memory | Slower initial load | [X] Bad |
| LAZY Fetch | Loads related data on demand | Lower memory footprint | Faster initial load | [OK] Good |
LAZY fetch type do in Spring Boot JPA?fetch = FetchType.EAGER inside relationship annotations.@ManyToOne(fetch = FetchType.EAGER), which is valid and correct.order.getItems() is called if items is marked with fetch = FetchType.LAZY?
@Entity
class Order {
@OneToMany(fetch = FetchType.LAZY)
private List<Item> items;
}
Order order = entityManager.find(Order.class, 1L);
// No call to getItems() yet
items are not loaded immediately.getItems() is called, triggering the fetch.@OneToMany(fetch = FetchType.LAZY) relationship, but you get a LazyInitializationException when accessing the collection outside a transaction. What is the likely cause?Author with a @OneToMany(fetch = FetchType.LAZY) relationship to Book. You want to display all authors with their books immediately to avoid multiple queries later. Which approach is best?