Sobes.tech
Junior — Middle

How to distinguish between the data loading modes FetchType Eager and Lazy, and what are their main differences?

sobes.tech AI

Answer from AI

In JPA (Java Persistence API), fetch modes determine when related entities are loaded from the database:

  • EAGER — related data is loaded immediately along with the main entity. This is convenient when related data is definitely needed, but can lead to excessive queries and load.

  • LAZY — related data is loaded only upon first access in the code. This saves resources but may cause a LazyInitializationException if the session is already closed.

Example:

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

Here, items will load only when calling order.getItems(), not immediately upon loading Order.

How to distinguish between the data loading modes… - sobes.tech