![]() |
VOOZH | about |
Lazy Loading and eager loading are both strategies for managing how data is fetched from a database or API in application development, particularly in System design. Lazy Loading delays loading related data until it's actually accessed, while Eager Loading retrieves all the necessary data in a single query.
Lazy Loading is a strategy where related data is loaded only when it is accessed for the first time.
Example:
Explanation: fetch = FetchType.LAZY tells Hibernate not to load employees until getEmployees() is called.
Eager Loading is a strategy where related data is fetched immediately along with the parent entity.
Example:
Explanation: fetch = FetchType.EAGER ensures that department is loaded immediately with the Employee object.
Feature | Lazy Loading | Eager Loading |
|---|---|---|
Data Fetch | On demand | Immediate |
Initial Load | Fast | Slower |
Memory Usage | Low | High |
Queries | More | Fewer |
Performance Risk | N+1 issue | Over-fetching |
Use Case | Large datasets | Small mandatory data |