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
Lazy Loading is a strategy where related data is loaded only when it is accessed for the first time.
- Default for @OneToMany and @ManyToMany relationships
- Uses proxy objects internally
- Reduces initial database load
Example:
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
@OneToMany(mappedBy = "department", fetch = FetchType.LAZY)
private List<Employee> employees;
}
Explanation: fetch = FetchType.LAZY tells Hibernate not to load employees until getEmployees() is called.
Eager Loading
Eager Loading is a strategy where related data is fetched immediately along with the parent entity.
- Default for @ManyToOne and @OneToOne
- Data is always available after loading the entity
Example:
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "department_id")
private Department department;
}
Explanation: fetch = FetchType.EAGER ensures that department is loaded immediately with the Employee object.
Difference Between Lazy Loading and Eager Loading
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 |