What is the difference between LAZY and EAGER fetching in JPA?
Options
- LAZY loads on first access; EAGER loads with the parent (Correct option)
- LAZY is always faster, while EAGER is always slower
- LAZY deletes the related data, while EAGER saves it
- 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.