Junior — Middle
How did you implement lazy data loading when using Hibernate?
sobes.tech AI
Answer from AI
In Hibernate, lazy loading of data can be implemented using the @OneToMany(fetch = FetchType.LAZY) annotation or similar for other relationships. This means that related entities are not loaded immediately when the main entity is fetched, but only upon the first access to them.
Example:
@Entity
public class User {
@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
private Set<Order> orders;
}
In this example, the orders collection will be loaded from the database only when user.getOrders() is called for the first time. This helps optimize performance by reducing the amount of data loaded if related objects are not needed immediately.