Sobes.tech
Junior — Middle

How does the FetchType.EAGER loading work in JPA when related objects are loaded?

sobes.tech AI

Answer from AI

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

This means that when fetching a JPA entity, it automatically performs additional SQL queries or joins to retrieve related entities and places them into the corresponding fields of the object.

For example, if you have an Order entity with a @OneToMany relationship to an OrderItem entity with FetchType.EAGER, then all related OrderItems will be loaded immediately when the Order is loaded.

Example:

@Entity
public class Order {
    @Id
    private Long id;

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "order")
    private Set<OrderItem> items;

    // getters and setters
}

When executing a query like entityManager.find(Order.class, id), JPA will perform an SQL JOIN or multiple queries to immediately fetch the Order and all related OrderItems.

The advantage of EAGER is convenience, as related data is immediately available. The disadvantage is potential performance reduction due to loading large volumes of data, which may not always be necessary.

How does the FetchType.EAGER loading work in JPA when… - sobes.tech