Java Spring Data and transactions
Where an ORM's convenience becomes an N+1 query nobody noticed, and where @Transactional silently does nothing.
4 concepts · 13 interview questions · 1 answered in depth
Answered in depth
How does @Transactional actually work, and when does it silently do nothing?
Spring wraps your bean in a proxy that opens a transaction before the method and commits after. Everything surprising follows from that: a self-invoked call bypasses the proxy entirely, and a checked exception commits instead of rolling back.
Asked constantlyintermediate2–8 yrs10 min read
What this topic covers
Every concept in spring data and transactions, and the questions each one gets asked as. Where a question links, it has a full write-up.
Repositories
An interface whose implementation Spring generates, deriving queries from method names or from an explicit @Query.
- How does Spring Data implement a repository interface you never wrote?
- CrudRepository versus JpaRepository?
- When do you write @Query instead of a derived method name?
@Transactional
A proxy opens a transaction before your method and commits or rolls back after — which is why the annotation is invisible to internal calls.
- How does @Transactional actually work?
- Why does @Transactional not work on a private or self-invoked method?
- Which exceptions trigger a rollback by default?
- What do propagation and isolation levels control?
The N+1 problem
Lazy associations loaded one row at a time inside a loop, turning one query into hundreds without any code looking wrong.
- What is the N+1 query problem, and how do you detect it?
- How do you fix N+1 — join fetch, entity graph, or batch size?
- Why does making everything EAGER make it worse?
Lazy loading and the persistence context
An entity is managed only inside its session; touching a lazy association after it closes throws.
- What causes LazyInitializationException?
- Why should an entity not be returned from a controller?
- What does the persistence context cache, and for how long?