Skip to the page

JPA and Hibernate · Trade-off

Lazy or eager loading

The interviewer asks

What are the default fetch types for @ManyToOne and @OneToMany in JPA? Many teams make every association lazy. Do you agree? Why?

Then

Follow-ups the interviewer asks next

  1. What does Hibernate give you for a lazy association before you touch it?
  2. What goes wrong with an EAGER @ManyToOne in a list query?
  3. If everything is lazy, how do you load what a screen needs?
  4. What does getReferenceById() do, and what was it called before?

The answer

What a strong answer covers

  • JPA defaults: @ManyToOne and @OneToOne are EAGER; @OneToMany and @ManyToMany are LAZY.
  • Lazy gives a proxy (to-one) or a collection wrapper; touching it runs a query, which needs an open session.
  • EAGER is fixed in the mapping for every use. A JPQL query for 500 orders doesn't join the eager customer automatically: Hibernate runs extra selects afterwards, an N+1 in disguise. You can't switch EAGER off for one query.
  • So: make all associations LAZY (add fetch = FetchType.LAZY on to-one) and fetch per use case with join fetch, @EntityGraph or DTO projections.
  • getReferenceById() (JPA getReference; Hibernate's old load(), removed in Hibernate 7) returns a proxy without a SELECT, handy for setting a foreign key; findById hits the database (or cache) and returns empty if the row is missing.

The red pen

Common traps

Avoid:"EAGER is faster because it's one query"; making everything EAGER to get rid of LazyInitializationException.

Practise this out loud

Say your answer out loud to an AI interviewer that follows up, and get a score for it.

Practise by voice

Practise questions like this out loud

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview