Skip to content
javahacks.dev
Hibernate

Fix LazyInitializationException in Spring Boot and Hibernate

Why Hibernate throws LazyInitializationException outside a transaction, how to confirm which cause you have and the fixes in order of preference.

6 min read
Summarize in AI
Flat illustration of a start button surrounded by Spring Boot starters, with the Spring Boot, Hibernate and Spring logos.

A Customer loads fine, the service returns, and the moment Jackson reads customer.getOrders() the request dies. The message is always some version of this one:

Text
org.hibernate.LazyInitializationException: could not initialize proxy [dev.javahacks.shop.Customer#1] - no Session

The cause is simple and the fix depends on why your code was reading outside the transaction. This post goes through the causes in the order they usually apply on Spring Boot 4 with Hibernate 7. For the mapping decisions behind it, see the Hibernate and JPA guide.

What the message means

A lazy association is a proxy or an uninitialized collection that remembers the session which created it. The first read triggers a select. If the session is already closed, Hibernate has nothing to run the query on, and throws. In Spring, the session normally lives as long as the @Transactional method that loaded the entity.

Cause 1: the entity left the transaction with its association untouched

This is the common one. The service loads an entity, returns it and the controller or the serializer reads the association:

java
@Service
class CustomerService {

    @Transactional(readOnly = true)
    public Customer find(long id) {
        return customers.findById(id).orElseThrow();   // orders is still a lazy proxy
    }
}

Confirm it by reading the stack trace: the failing frame is in a controller, a mapper or jackson, never inside the service. The fix is to load the data inside the transaction and return only what the caller needs.

java
public interface CustomerRepository extends JpaRepository<Customer, Long> {

    @EntityGraph(attributePaths = "orders")
    Optional<Customer> findWithOrdersById(Long id);
}

@EntityGraph tells Spring Data to fetch orders in the same query. A join fetch in a @Query does the same. If the caller needs only a few fields, a DTO projection is cleaner still, because no managed entities leave the service:

java
public record CustomerSummary(long id, String name, long orderCount) {}

@Query("select new dev.javahacks.shop.CustomerSummary(c.id, c.name, size(c.orders)) from Customer c where c.id = :id")
Optional<CustomerSummary> summary(@Param("id") long id);

Cause 2: open-in-view hid it in development and you turned it off

spring.jpa.open-in-view defaults to true, which keeps a session open until the response is written. Every lazy read in a controller works. Setting it to false in production, or in tests, is when the same code starts throwing. Do not switch it back on to make the error go away. The setting is covered in Spring Boot from first project to production, and the consequence of leaving it on is a connection held for the entire request.

Cause 3: the service method is not transactional

If the method that loads the entity has no transaction, Spring Data opens a short one per repository call, and the session closes before your code touches the association. Add @Transactional to the service method, and check that the call really goes through the proxy. A call from another method in the same class does not, as [@Transactional on self-called methods](/library/transactional-not-working-fix-self-called) explains.

Cause 4: a detached entity from a cache or a session attribute

An entity stored in an HTTP session or a Spring cache outlives its session by definition. Reading a lazy field on it always fails. Cache DTOs or ids, never managed entities.

Fixes that make it worse

Tempting fixWhat it costs
fetch = FetchType.EAGER on the associationEvery query that loads the entity now loads the association, including ones that never needed it
spring.jpa.open-in-view=trueA database connection held for the whole request, including slow clients
hibernate.enable_lazy_load_no_trans=trueA new session and connection per lazy read, and an N plus 1 you cannot see
@Transactional on the controllerTransaction held across view rendering and serialization

The Hibernate user guide treats the last property as an anti-pattern for these reasons. Read the fetching section of the Hibernate documentation for the full set of strategies. If fixing this exception makes the query count jump instead, you have swapped it for the N plus 1 problem.

A reproduction in one test

A fix you cannot reproduce is a fix you cannot keep. The failure takes a few lines to provoke, which also gives you a regression test:

java
@DataJpaTest
class LazyLoadingTest {

    @Autowired CustomerRepository customers;
    @Autowired TestEntityManager em;

    @Test
    void readingACollectionOutsideTheSessionFails() {
        Customer saved = em.persistAndFlush(new Customer("Ada", List.of(new Order("o-1"))));
        em.clear();

        Customer loaded = customers.findById(saved.getId()).orElseThrow();
        em.getEntityManager().close();             // simulate the session ending

        assertThrows(LazyInitializationException.class, () -> loaded.getOrders().size());
    }
}

The same test, run through the repository method with @EntityGraph, should read the orders without error after the session is closed. Keep both tests: one documents the failure, the other pins the fix, and the second one fails the day someone removes the graph annotation.

Four ways to load exactly what the caller needs

The right fix depends on how the data is used. These are the four tools, with the situation each one fits:

java
public interface CustomerRepository extends JpaRepository<Customer, Long> {

    // 1. Entity graph: simple, declarative, keeps entities
    @EntityGraph(attributePaths = "orders")
    Optional<Customer> findWithOrdersById(Long id);

    // 2. Join fetch: explicit JPQL, one query
    @Query("select c from Customer c left join fetch c.orders where c.id = :id")
    Optional<Customer> loadWithOrders(@Param("id") Long id);

    // 3. DTO projection: no entities leave the service
    @Query("""
        select new dev.javahacks.shop.CustomerSummary(c.id, c.name, count(o))
        from Customer c left join c.orders o
        where c.id = :id
        group by c.id, c.name
        """)
    Optional<CustomerSummary> summary(@Param("id") Long id);

    // 4. Interface projection: Spring generates the proxy
    interface NameOnly {
        Long getId();
        String getName();
    }
    List<NameOnly> findByNameStartingWith(String prefix);
}

Use the entity graph when the caller truly needs the entity and its children. Use the DTO projection when the caller needs numbers or a few columns, which is most read endpoints. The interface projection is a convenient middle for lists. Avoid fetching two collections with one join fetch, because the result is a Cartesian product and Hibernate may refuse with MultipleBagFetchException: fetch one collection with the join and the other with a second query, or use batch fetching.

Batch fetching when you cannot join

Sometimes a list of customers is loaded and each one's orders are read later in a loop. A join fetch on the list query would duplicate the customer rows, and per-customer queries are the N plus 1 problem. Batch fetching loads the collections of many parents in one in query:

YAML
spring:
  jpa:
    properties:
      hibernate:
        default_batch_fetch_size: 50

With this, reading the orders of 50 customers triggers one query for the first collection and loads the other 49 in the same statement. It does not remove the need to stay inside a transaction. It reduces how many statements the lazy loads cost once you are inside it.

Keep the transaction boundary on the service

A final detail that decides whether the fix holds: where the transaction starts and what the method returns. A read method that maps to a DTO inside the transaction cannot leak a lazy proxy:

java
@Service
class CustomerQueries {

    private final CustomerRepository customers;

    CustomerQueries(CustomerRepository customers) {
        this.customers = customers;
    }

    @Transactional(readOnly = true)
    public CustomerView view(Long id) {
        Customer c = customers.findWithOrdersById(id).orElseThrow(CustomerNotFound::new);
        return new CustomerView(
            c.getId(),
            c.getName(),
            c.getOrders().stream().map(o -> new OrderLine(o.getId(), o.total())).toList());
    }
}

readOnly = true tells Spring and Hibernate that no flush is needed, which saves work and signals intent. The view is a record made of plain values, so the controller and Jackson cannot trigger a lazy load even by accident. If an entity must leave the service, the exception is the system working as designed: it tells you a caller depends on data nobody loaded on purpose.

Where this does not apply

If the exception names a collection role and you are inside a @Transactional method, the session is open and something else is wrong: a StatelessSession, an entity loaded in a different transaction and passed in, or a read from an @Async thread. Trace where the entity was loaded, not where it failed. The Spring Data JPA reference documents the behavior in detail.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.