Junior — Middle
What is the significance of the default loading strategy in Hibernate for associated entities?
sobes.tech AI
Answer from AI
In Hibernate, the default fetch strategy for associated entities depends on the type of association:
-
For
@ManyToOneand@OneToOneassociations, EAGER fetching is used by default, meaning related entities are loaded immediately along with the main entity. -
For
@OneToManyand@ManyToManyassociations, LAZY fetching is used by default, meaning related collections are loaded only upon first access.
This behavior can be overridden using the @FetchType.LAZY or @FetchType.EAGER annotations.
Example:
@Entity
public class Order {
@ManyToOne(fetch = FetchType.EAGER) // default
private Customer customer;
@OneToMany(fetch = FetchType.LAZY) // default
private List<OrderItem> items;
}
Thus, Hibernate optimizes data loading by either loading related objects immediately or on demand, depending on the association type.