Junior — Middle
Explain the concept of lazy loading in Hibernate and how it affects data handling.
sobes.tech AI
Answer from AI
Lazy Loading in Hibernate is a fetch strategy where related entities or collections are loaded only when they are actually accessed, rather than immediately when the main entity is loaded.
This helps optimize performance by reducing the amount of data fetched from the database and decreasing memory and network load. For example, if an object has a related collection that is not needed in the current context, Hibernate will not load it from the database until it is accessed.
However, lazy loading should be used carefully to avoid issues such as LazyInitializationException, which occurs when attempting to access lazily loaded data outside of a Hibernate session.
Example:
@Entity
public class User {
@OneToMany(fetch = FetchType.LAZY)
private Set<Order> orders;
// orders are not loaded immediately, only when getOrders() is called
}