Sobes.tech
Junior — Middle

How does Hibernate's Lazy and Eager loading behavior differ when loading related entities?

sobes.tech AI

Answer from AI

In Hibernate, the behavior of loading related entities is determined by Lazy and Eager loading strategies.

  • Lazy Loading: related entities are loaded only upon first access. Initially, only the main entity is loaded, and related data is fetched later when accessed. This helps save resources and reduce the amount of data loaded immediately.

  • Eager Loading: related entities are loaded immediately along with the main entity in a single query (or using join). This is convenient when related data is definitely needed, to avoid additional queries.

Example:

@Entity
class Author {
    @OneToMany(fetch = FetchType.LAZY) // or FetchType.EAGER
    private Set<Book> books;
}

If FetchType.LAZY is specified, author's books are loaded only when author.getBooks() is called. If FetchType.EAGER, books are loaded immediately with the author.

How does Hibernate's Lazy and Eager loading behavior… - sobes.tech