Junior — Middle
How do the normal and lazy loading modes in JPA differ?
sobes.tech AI
Answer from AI
In JPA, fetch modes determine when related entities or collections are loaded from the database:
-
EAGER loading — related data is loaded immediately along with the main entity. This is convenient when related data is always needed, but can lead to excessive queries and reduced performance.
-
LAZY loading — related data is loaded only upon first access in the code. This conserves resources, especially if related data is not always required.
Example:
@Entity
public class Order {
@OneToMany(fetch = FetchType.LAZY)
private List<Item> items;
}
Here, the list of items will be loaded from the database only when order.getItems() is called.