Sobes.tech
Junior — Middle

Can you explain the behavior mechanism of FetchType.LAZY loading strategy in ORM systems?

sobes.tech AI

Answer from AI

In ORM systems like Hibernate, the FetchType.LAZY loading strategy means that related entities (associations) are not loaded from the database immediately along with the main entity. Instead, they are loaded only when first accessed in the code.

For example, if you have an entity Order with a collection items marked as LAZY, then when loading the order from the database, the items collection will not be loaded immediately. The first time you call order.getItems(), ORM will execute a separate query to fetch this data.

This helps save resources and reduce load time, especially if related data is not always needed. However, you need to be careful with the session/transaction: if the session is closed and you try to access a LAZY-loaded collection, a LazyInitializationException will occur.

Example:

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

    // getters and setters
}

// When loading Order, items are not loaded immediately
Order order = entityManager.find(Order.class, id);
// Here, items are not yet loaded
List<Item> items = order.getItems(); // This triggers a separate database query