Sobes.tech
Junior — Middle

Could you explain the concept of Eager loading in Hibernate and how it differs from Lazy?

sobes.tech AI

Answer from AI

In Hibernate, the concept of Eager loading means that related objects are loaded immediately along with the main object, usually through a JOIN in SQL. This is convenient when related data is definitely needed to avoid additional queries.

Lazy loading defers the loading of related objects until they are explicitly accessed. Hibernate performs a separate query to the database only when necessary.

Example:

@Entity
public class Order {
    @OneToMany(fetch = FetchType.LAZY) // or FetchType.EAGER
    private Set<Item> items;
}
  • With FetchType.EAGER, all related items are loaded immediately when the order is loaded.
  • With FetchType.LAZY, items are loaded only when order.getItems() is called.

Eager loading can improve performance if the data is definitely needed, but increases load when overused. Lazy loading saves resources but can lead to the "N+1 query" problem if used improperly.

Could you explain the concept of Eager loading in… - sobes.tech