Sobes.tech
Junior — Middle

Can you explain how the Lazy loading strategy works in JPA/Hibernate?

sobes.tech AI

Answer from AI

Lazy loading strategy in JPA/Hibernate means that related entities are not loaded immediately when the main entity is loaded, but only upon the first access to them. This helps optimize performance by reducing the amount of data loaded from the database.

For example, if you have an Order entity with a collection of items, when loading the order from the database, Hibernate will not load all items immediately. They will be loaded only when you call order.getItems().

Example:

@Entity
public class Order {
    @OneToMany(fetch = FetchType.LAZY)
    private List<Item> items;
}

With this approach, Hibernate creates a proxy object for the items collection, and the actual database query is executed only when you access this collection.