Middle
What is the difference between lazy and eager loading?
sobes.tech AI
Answer from AI
Lazy loading defers the initialization of an object until the first time it is accessed. Eager loading initializes the object immediately when the main object containing the reference is loaded.
Differences:
| Characteristic | Lazy Loading | Eager Loading |
|---|---|---|
| Loading Time | At first use | When loading the main object |
| Load | Distributed over time | All at once at the start |
| Memory | Saves memory initially | May require more memory immediately |
| Performance | Better when working with part of data | Can be faster if all data is needed immediately |
Example in Hibernate:
// Lazy loading
@Entity
public class Order {
@OneToMany(fetch = FetchType.LAZY)
private List<Item> items;
}
// Eager loading
@Entity
public class Order {
@OneToMany(fetch = FetchType.EAGER)
private List<Item> items;
}