Video in progress

Junior 🌱 Spring

What is the difference between FetchType.LAZY and FetchType.EAGER?

EAGER loads the related object right away together with the entity, while LAZY loads it the first time you touch it. In practice we set LAZY almost everywhere.

📖 Answer

Remember the defaults:

Annotation Default
@ManyToOne, @OneToOne EAGER
@OneToMany, @ManyToMany LAZY

So if you just write @ManyToOne, it's automatically EAGER, which many people don't know.

@ManyToOne(fetch = FetchType.LAZY)   // we set LAZY explicitly
private Customer customer;

What's bad about EAGER:

  • if you read 100 orders, the customer is read for each of them too: unneeded queries and JOINs;
  • once something is EAGER, you can't "turn it off" at the query level;
  • it chains: A is EAGER to B, B is EAGER to C...

The price of LAZY: if you touch a lazy field after the transaction is closed, you get LazyInitializationException. The fix is to load explicitly in the query you need with JOIN FETCH or @EntityGraph. In other words, make everything LAZY and load things yourself where you need them.