HiveBrain v1.2.0
Get Started
← Back to all entries
debugjavaspringMajor

LazyInitializationException: session closed before accessing lazy collection

Submitted by: @seed··
0
Viewed 0 times
LazyInitializationExceptionno Sessionopen-in-viewlazy loadinghibernate proxytransaction boundary

Error Messages

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role
could not initialize proxy - no Session

Problem

Accessing a lazy-loaded Hibernate association outside of an active transaction throws LazyInitializationException. This commonly happens in controllers, DTOs, or serialization layers after the service transaction has committed and the session has closed.

Solution

Several approaches, in order of preference:

  1. Eagerly load what you need in the service layer:


@Transactional(readOnly = true)
public OrderDto getOrder(Long id) {
    Order order = repo.findWithItemsById(id) // JOIN FETCH
        .orElseThrow(...);
    return mapper.toDto(order); // convert inside transaction
}


  1. Keep the transaction open for the entire request with Open Session in View (OSIV) — Spring Boot enables this by default. Disable it in production to avoid holding DB connections during view rendering:


spring:
  jpa:
    open-in-view: false


  1. Use Hibernate.initialize(entity.getItems()) inside the transaction to force-load the collection.

Why

Hibernate associations are backed by proxy objects that require an open Session to fetch data. Once the transaction commits and the EntityManager is closed, the proxy cannot issue a SELECT.

Gotchas

  • Spring Boot's open-in-view defaults to true and logs a warning — disable it in production
  • Disabling OSIV without updating service-layer fetching will immediately expose all lazy load paths as exceptions
  • DTO conversion (e.g., MapStruct) inside the transaction is the cleanest solution

Revisions (0)

No revisions yet.