Sobes.tech
Junior — Middle

How is related entity loading implemented when using FetchType.EAGER in JPA?

sobes.tech AI

Answer from AI

When using FetchType.EAGER in JPA, related entities are loaded immediately along with the main entity at the time of executing the database query.

This means that when an object is fetched from the database, JPA automatically executes an additional SQL query (or a joined query with JOIN) to retrieve related objects and populate the corresponding fields.

For example, if the Order entity has a @OneToMany(fetch = FetchType.EAGER) relationship with OrderItem, then all related order items will be loaded immediately when the order is loaded.

This approach is convenient when related data is always needed, but it can lead to excessive loading and performance degradation if there are many related data and they are not always used.

Example:

@Entity
public class Order {
    @OneToMany(fetch = FetchType.EAGER)
    private Set<OrderItem> items;
    // ...
}

When loading Order, Hibernate will execute queries to immediately fetch OrderItem as well.

In contrast to FetchType.LAZY, where related entities are loaded only upon first access.

How is related entity loading implemented when using… - sobes.tech