What mechanisms does JPA use to organize the loading of related objects?
sobes.tech AI
Answer from AI
JPA uses two main mechanisms for organizing the loading of related objects:
-
Eager loading (EAGER) — related objects are loaded immediately along with the main object. This is convenient when related data is definitely needed, but can lead to excessive loading and reduced performance.
-
Lazy loading (LAZY) — related objects are loaded only upon first access. This allows saving resources by loading data as needed.
These mechanisms are set using annotations like @OneToMany, @ManyToOne, @OneToOne, etc., for example:
@OneToMany(fetch = FetchType.LAZY)
private List<Order> orders;
JPA also uses proxy objects to implement lazy loading, replacing real related objects with stubs that load data upon the first call.
The choice between EAGER and LAZY depends on specific performance requirements and application logic.