Hibernate cannot initialize a lazy collection or proxy in Spring Boot
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of roleShort 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.
Fix it fast
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/2Match what you see, then jump to its fix
- 1
The 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
The 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
The method has @Transactional and the exception still appears inside it@Transactional is on the method but never takes effectFix
- 1
What does the error look like?
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of rolecould 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/itemsConfirmed by docs.hibernate.org
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/java2Fix
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=trueConfirmed by docs.spring.io
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/java2Fix
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 testConfirmed by docs.spring.io
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
Databases
H2 in PostgreSQL mode still behaves differently from PostgreSQL
Names or null ordering differ from PostgreSQL in test results
H2 compatibility modes are switched on in the JDBC URL and cover only a small part of the differences between databases.
4 causes, each with a fixDatabases
Hibernate fails on a CREATE or ALTER TABLE statement at startup
Error executing DDL "alter table events drop foreign key FKg0mkvgsqn8584qoql6a2rxheq" via JDBC Statement
Hibernate generated a CREATE, ALTER or DROP statement and MySQL refused it.
3 causes, each with a fixDatabases
Java cannot log in to MySQL 8: authentication plugin caching_sha2_password not supported
ERROR 2061 (HY000): Authentication plugin 'caching_sha2_password' reported error: Authentication requires secure connection.
MySQL 8 accounts use the caching_sha2_password plugin by default, and Connector/J releases before 8.0.9 cannot use it.
3 causes, each with a fixDatabases
Hibernate insert fails: column is of type bit but expression is of type boolean
ERROR: column "active" is of type bit but expression is of type boolean
PostgreSQL has a real boolean type and a separate bit type, and it will not convert one to the other on insert.
3 causes, each with a fixDatabases
Spring Boot cannot configure a DataSource for PostgreSQL
Failed to determine a suitable driver class
Spring Boot builds a pooled DataSource only when it has a JDBC URL and a loadable driver.
3 causes, each with a fixDatabases
Spring Boot stops at startup with flywayInitializer failing
Caused by: org.flywaydb.core.api.FlywayException
flywayInitializer is the bean that runs your migrations at startup, so any migration problem surfaces as its BeanCreationException.
4 causes, each with a fix