Skip to content
Commitwise
Menu

Lazy loading

Loading related data only when it is first used, instead of together with the object that refers to it.

Definition

In JPA and Hibernate, a lazy association (author.books, or a @ManyToOne marked LAZY) is a placeholder until code touches it; then Hibernate runs a query to fill it. This avoids loading data nobody needs, but it needs an open session: touching a lazy association after the transaction ends throws LazyInitializationException, and touching one per item in a loop causes the N+1 problem.

In practice

Loading 20 orders and then reading order.getLines() for each runs 1 + 20 queries unless the lines are fetched with a join or in a batch.

Learn it in context

Lessons that use this term.

Related terms

Esc

Type to search the whole site.