Hibernate Eager/Lazy Loading (original) (raw)

Last Updated : 28 Mar, 2026

Eager and Lazy Loading in Hibernate are strategies that define how related data is fetched from the database. They control whether associated entities are loaded immediately with the parent object or only when needed, helping balance performance and resource usage.

fetch_types

**Note: You can specify the fetch type of an association by using the fetch attribute of the @OneToMany, @ManyToOne, @OneToOne, or @ManyToMany annotations.

**LAZY Loading

FetchType.LAZY is used to delay the loading of associated entities until they are actually accessed. This helps optimize performance by avoiding unnecessary data retrieval at the time of the main entity loading.

@Entity public class Employee { @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "address_id") private Address address;

// other fields and methods

}

`

**Note: In this example, the Address entity associated with an Employee will be fetched lazily when it is accessed for the first time.

EAGER Loading

FetchType.EAGER means the associated entity is loaded immediately along with the main entity. It ensures that related data is always available at the time of fetching the parent entity.

@Entity public class Employee { @OneToOne(fetch = FetchType.EAGER) @JoinColumn(name = "address_id") private Address address;

// other fields and methods

}

`

**Note: In this example, the Address entity associated with an Employee will be fetched eagerly when the Employee is loaded from the database.

Eager Loading Vs Lazy Loading

Feature Eager Loading Lazy Loading
Definition Loads related data immediately with the parent entity Loads related data only when it is accessed
Fetching Time At the time of initial query On-demand (when getter is called)
Performance Can be slower if unnecessary data is fetched Improves performance by loading only required data
Memory Usage Higher (loads all related data) Lower (loads data only when needed)
Use Case When related data is always required When related data is not always needed
Annotation FetchType.EAGER FetchType.LAZY
Database Queries Fewer queries but heavier data More queries but optimized data loading
Risk Over-fetching data May cause LazyInitializationException