Repaso
EspaƱol
Spring, JPA & Java WebIntermediateSPR-18

What is the difference between LAZY and EAGER fetching in JPA?

Options

  1. LAZY loads on first access; EAGER loads with the parent (Correct option)
  2. LAZY is always faster, while EAGER is always slower
  3. LAZY deletes the related data, while EAGER saves it
  4. There is no difference at all between the two modes

Answer

LAZY loads related data only when you first access it; EAGER loads it immediately together with the parent

Why

A User may have many Orders. With EAGER, loading a user also loads all their orders right away, even if you never use them. With LAZY, orders are loaded from the database only when you first call user.getOrders().

Defaults: @OneToMany is LAZY, @ManyToOne is EAGER.

LAZY avoids loading too much, but accessing a lazy field after the session/transaction has closed throws LazyInitializationException. A common recommendation is to use LAZY and fetch what you need explicitly (JOIN FETCH or @EntityGraph).

Remember

Prefer LAZY, fetch explicitly what a use case needs.

Key terms

Practice this question in Repaso