Lazy loading is a fetching strategy in Hibernate where an entity or its associated collections are not retrieved from the database until the code actually accesses them, rather than being loaded eagerly along with the parent object.
Key Points: • It's the default fetch type for @OneToMany and @ManyToMany associations in JPA/Hibernate. • Accessing a lazy association outside of an open Session (e.g. after the session closes) causes a LazyInitializationException. • Hibernate implements lazy loading using proxies or bytecode-enhanced collection wrappers that trigger a query on first access. • It reduces unnecessary data transfer and memory usage when related data isn't always needed. • The opposite, eager fetching (FetchType.EAGER), loads associations immediately along with the parent, which can hurt performance if overused.
Example: Loading a Department entity with a lazy @OneToMany list of Employees doesn't hit the database for employees at all until code calls department.getEmployees(), at which point Hibernate issues the query to fetch them.
Code Example:
@Entity
public class Department {
@OneToMany(mappedBy = "department", fetch = FetchType.LAZY)
private List<Employee> employees;
}Interview Tip: A concise interview answer is:
"Lazy loading defers fetching an association until it's actually accessed in code, using a proxy that triggers the real query on first use. It's the default for collections in Hibernate and helps avoid pulling in data you don't need, but accessing it after the session is closed throws a LazyInitializationException."