JPA and Hibernate · Trade-off
Lazy or eager loading
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe 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
- What does Hibernate give you for a lazy association before you touch it?
- What goes wrong with an EAGER @ManyToOne in a list query?
- If everything is lazy, how do you load what a screen needs?
- What does
getReferenceById()do, and what was it called before?
The answer
What a strong answer covers
- JPA defaults:
@ManyToOneand@OneToOneare EAGER;@OneToManyand@ManyToManyare 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
customerautomatically: 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.LAZYon to-one) and fetch per use case with join fetch,@EntityGraphor DTO projections. getReferenceById()(JPAgetReference; Hibernate's oldload(), removed in Hibernate 7) returns a proxy without a SELECT, handy for setting a foreign key;findByIdhits 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 voicePractise 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.