Card 02/ 07
LazyInitializationException: A Lazy Collection Read Outside Its Transaction
A collection that was never loaded, read after the only transaction that could load it has closed.
JPA loads a @OneToMany collection lazily by default: the entity, the object mapped to the rider's row, arrives with a stand-in for the collection, and the real rows are fetched the first time the code reads it. That fetch needs an open persistence context (JPA's record of the entities it is tracking in the current transaction), so reading the collection after its transaction has closed throws LazyInitializationException.
A rider is loaded through the repository, and a moment later the code asks how many rides they have:
void accessRidesOutsideTransaction(Long id) {
RiderEntity rider = repo.findById(id).orElseThrow();
// repo.findById()'s own transaction already closed by the time execution gets here
System.out.println(rider.rides.size());
}OUTSIDE transaction -> LazyInitializationException: failed to lazily initialize a collection of role: rides.RiderEntity.rides: could not initialize proxy - no SessionA repository method runs in its own short transaction by default, which is how findById works with no transaction around the calling method. By the time .size() runs, that transaction has closed, and the stand-in has nothing left to fetch its data with.
Spring Boot hides this inside web requests: its open-in-view setting, on by default, keeps the persistence context open for the whole request, and Boot logs a warning about it at startup. The exception then appears in the places open-in-view does not cover, such as scheduled jobs, tests and background tasks, or everywhere once the setting is turned off.
The fix is to read the collection inside a transaction, by putting @Transactional on the method that uses it, or to load it together with its owner in the query. Spring Data JDBC has no lazy loading to fail: it loads an aggregate (an entity together with the objects it owns, saved and loaded as one) in full, every time.
← → move through sections and cards