Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Databases and Redis

Hibernate cannot initialize a lazy collection or proxy in Spring Boot

Errororg.hibernate.LazyInitializationException: failed to lazily initialize a collection of role

Short answer

A lazy collection or proxy is loaded on first access, and that needs an open Hibernate session. LazyInitializationException means the code touched it after the session closed. Load what you need before the session ends: inside a working @Transactional method, with an entity graph on the repository method, or by mapping to a DTO.

  • Applies to Spring Boot 3.4, Spring Data JPA 3.4, Hibernate ORM 6.6, Java 21
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Find the first line of the stack trace that is your own code. That is the place where a lazy field is read, and it tells you which of the causes below applies.

    grep -rn "open-in-view" src/main/resources/
  2. 2Match what you see, then jump to its fix

    1. 1The exception is thrown in a controller, a scheduler or a JSON serializer, never inside the service method that loaded the entityThe lazy field is read after the session has closedFix
    2. 2The collection is needed every time this query is used, so the exception repeats for the same callThe repository method does not fetch the associationFix
    3. 3The method has @Transactional and the exception still appears inside it@Transactional is on the method but never takes effectFix

What does the error look like?

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

Cause 1 of 3

The lazy field is read after the session has closed

1Check

Hibernate documents the exception as an attempt to reach unfetched data outside an open stateful Session. Spring Boot opens a session for the whole web request by default (OpenEntityManagerInViewInterceptor). If spring.jpa.open-in-view is false, or the code runs outside a web request, the session ends when the service method returns.

grep -rn "open-in-view" src/main/resources/

2Fix

Read the lazy field while the transaction is still open: put the read inside a @Transactional service method and return plain data (a DTO or a list), not the entity.

@Service
public class OrderService {
    private final OrderRepository orders;

    public OrderService(OrderRepository orders) { this.orders = orders; }

    @Transactional(readOnly = true)
    public List<String> itemNames(Long orderId) {
        Order order = orders.findById(orderId).orElseThrow();
        return order.getItems().stream().map(Item::getName).toList();
    }
}

3Verify

Call the endpoint again. The same request now returns data instead of the exception.

curl -s http://localhost:8080/orders/1/items

Confirmed by docs.hibernate.org

Did this fix it?

Cause 2 of 3

The repository method does not fetch the association

1Check

Spring Data documents that the default fetch mode of a collection is lazy. A query method that returns the parent alone leaves the collection unloaded.

grep -n "@OneToMany\|@ManyToMany\|@ManyToOne" -r src/main/java

2Fix

Add an entity graph to the repository method so the collection is loaded in the same query.

public interface OrderRepository extends JpaRepository<Order, Long> {

    @EntityGraph(attributePaths = { "items" })
    Optional<Order> findById(Long id);
}

3Verify

Turn on show-sql and confirm the items are loaded by one statement with a join.

spring.jpa.show-sql=true

Confirmed by docs.spring.io

Did this fix it?

Cause 3 of 3

@Transactional is on the method but never takes effect

1Check

Spring only starts a transaction for calls that come in through the proxy. A call from another method of the same class is not intercepted, and on interface-based proxies the method must be public.

grep -n "@Transactional" -r src/main/java

2Fix

Move the transactional method into a separate bean and call it from there, or call it through an injected reference instead of this.

@Service
public class OrderReader {
    @Transactional(readOnly = true)
    public int itemCount(Order order) {
        return order.getItems().size();
    }
}

3Verify

Call it from the other bean and check that the exception is gone.

mvn -q test

Confirmed by docs.spring.io

Did this fix it?

How do I stop it coming back?

  • Return DTOs from services and keep entities inside the transaction.
  • Decide per query which associations are needed and fetch those with an entity graph.
  • Do not rely on open-in-view: the Spring Boot docs say it is on by default and can be switched off with spring.jpa.open-in-view=false.
  • Add a test that calls the service from outside any transaction, as a controller does.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.