Java: LazyInitializationException could not initialize proxy
A lazy association was read after the session closed. Fetch it inside the transaction, use a join fetch or entity graph, or map a DTO instead.

Introduction & Quick Summary
An endpoint that reads a collection returns 500 and logs this:
org.hibernate.LazyInitializationException: could not initialize proxy
[com.acme.shop.Order#42] - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:176)
at com.acme.shop.Order.getItems(Order.java:88)
at com.acme.shop.web.OrderController.toDto(OrderController.java:57)Quick answer: the entity was loaded inside a transaction, the transaction ended, and then code touched a lazy association. The proxy that represents items has no session left to query with, so it throws instead of returning an empty list.
Three fixes, in order of preference:
// 1. fetch what the response needs, in the query
@Query("select o from Order o join fetch o.items where o.id = :id")
Optional<Order> findWithItems(@Param("id") Long id);
// 2. shape the response inside the transaction
@Transactional(readOnly = true)
public OrderDto getOrder(Long id) {
return orderRepository.findById(id)
.map(o -> new OrderDto(o.getId(), o.getItems().size()))
.orElseThrow();
}
// 3. widen the session (Spring Boot default) — a safety net, not a design
spring.jpa.open-in-view=trueThe exception is not a mapping bug. It is the persistence context being closed while an object graph still points at unloaded data. Everything below is about deciding where the load should happen: in the query, in the service transaction, or during serialization.
Core Mechanics, Signatures & Reproducible Setup
Hibernate returns a proxy for a lazy association: a subclass instance holding an identifier and a reference to the session that created it. Any method call other than getId() triggers initialization, which requires an open session for that entity.
The session's lifetime is the @Transactional boundary (or the servlet request, with Open Session in View). Once that scope ends, session becomes null on the proxy and the next access throws.
@Entity
public class Order {
@Id private Long id;
@OneToMany(mappedBy = "order", fetch = jakarta.persistence.FetchType.LAZY)
private List<OrderItem> items = new ArrayList<>();
@ManyToOne(fetch = jakarta.persistence.FetchType.LAZY)
private Customer customer;
}A reproducible Spring Boot test that fails the same way:
@DataJpaTest
class OrderLazyTest {
@Autowired OrderRepository orders;
@Autowired TestEntityManager em;
@Test
void lazyCollectionOutsideTransaction() {
Order saved = orders.save(new Order());
em.flush();
em.clear();
Order found = orders.findById(saved.getId()).orElseThrow();
assertThatThrownBy(() -> found.getItems().size())
.isInstanceOf(org.hibernate.LazyInitializationException.class);
}
}@DataJpaTest wraps each test in a transaction, so a plain assertion would pass; the exception needs a scope that ends — which is exactly what happens in production when the controller runs after the service method returns.
Key Comparison Table
| Where it throws | Why | Fix |
|---|---|---|
| Controller after service returns | transaction ended | fetch in the query or return a DTO |
| Jackson serializing an entity | serializer walks lazy fields | DTO or @JsonIgnore on the back-reference |
@Async method | new thread, no session | pass loaded data or re-open a transaction |
| Template rendering (Thymeleaf) | view runs after commit | OSIV, or load what the view needs |
equals/hashCode during a Set insert | proxy initialized implicitly | compare ids, not fields |
Test after em.clear() | detached entity | assert inside the transaction |
| Fetch approach | Query cost | Pagination safe | Use when |
|---|---|---|---|
join fetch | one query | no, for collections | a single aggregate root |
@EntityGraph | one query | depends on shape | repository methods |
@BatchSize / default_batch_fetch_size | 1 + n/k queries | yes | lists of entities |
| DTO projection | one query, exact columns | yes | read endpoints |
EAGER everywhere | unpredictable joins | no | almost never |
| Setting | Default | Effect |
|---|---|---|
spring.jpa.open-in-view | true | session spans the request; hides the bug |
hibernate.default_batch_fetch_size | unset | batches lazy loads by id |
@Transactional(readOnly = true) | — | still a session, still ends at return |
hibernate.enable_lazy_load_no_trans | false | opens a temp session per access, discouraged |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Serialization is not a transaction
Returning an entity from a controller looks convenient until the serializer walks a lazy field after the service committed:
@GetMapping("/orders/{id}")
public Order get(@PathVariable Long id) {
return orderService.find(id); // transaction already closed
}Map to a record inside the transactional method. The DTO is also the place to decide what the API actually exposes:
public record OrderDto(Long id, String customerName, int itemCount) {
static OrderDto of(Order o) {
return new OrderDto(o.getId(), o.getCustomer().getName(), o.getItems().size());
}
}2. Self-invocation skips the proxy
@Transactional works through a proxy. A call from inside the same bean never crosses it, so no transaction starts and the lazy load fails even though the annotation is present:
@Service
public class OrderService {
public OrderDto load(Long id) {
return loadInternal(id); // no proxy, no transaction
}
@Transactional(readOnly = true)
public OrderDto loadInternal(Long id) { ... }
}Move the annotated method to another bean, or inject the proxy through ObjectProvider<OrderService> and call it from outside.
3. Open Session in View: what it does and hides
Spring Boot enables OSIV by default and logs a warning at startup. The session stays open for the whole request, so controller-level access works — until you disable it and the same code throws:
spring:
jpa:
open-in-view: falseDisabling it is the right direction for a JSON API, but do it together with DTO mapping; otherwise every endpoint that touched an association starts throwing.
4. join fetch plus pagination
Fetching a collection with a join and Pageable makes Hibernate page in memory and log firstResult/maxResults specified with collection fetch; applying in memory:
// two-step: page the ids, then fetch the graph
Page<Long> ids = orderRepository.findIds(pageable);
List<Order> orders = orderRepository.findWithItemsByIdIn(ids.getContent());The alternative is @BatchSize(size = 50) on the collection, which keeps pagination in SQL and issues a bounded number of follow-up selects.
5. Proxies in equals, hashCode and Set
Calling equals on a proxy can initialize it, and a Lombok @Data entity compares every field:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Order other)) return false;
return id != null && id.equals(other.getId()); // getId() does not initialize
}getId() is safe on a proxy because the identifier is already known; getItems() is not.
6. Async, scheduled work and new threads
@Async, CompletableFuture.supplyAsync and @Scheduled methods run outside the caller's transaction and outside any request-bound session:
@Async
public void export(Long orderId) {
// lazy access here throws: no session in this thread
}Load the data in a transactional method first and pass the DTO into the async task, or annotate the async method itself with @Transactional so it opens its own session.
The SQL formatter is useful when you want to confirm what the generated join actually does, and the SQL schema designer helps sketch the association before changing fetch types.
Common Compilation/Runtime Mistakes & Version Gotchas
- Switching everything to
EAGER. It removes the exception and replaces it with cartesian products and N+1 selects that are harder to find. - Catching
LazyInitializationException. Swallowing it returns partial data; the load belongs inside the transaction. Hibernate.initialize()at every call site. It opens a temporary session and hides the boundary problem; use it only as a deliberate, local exception.getReferenceByIdversusfindById. The reference is a proxy; reading a lazy field outside the transaction throws exactly this error.- Lombok
@Dataon entities. GeneratedtoString,equalsandhashCodetouch every field, including lazy ones, and can trigger loads in logs. - Spring Boot 3 and Jakarta imports. Mixing
javax.persistencewithjakarta.persistenceannotations produces entities whose fetch types are ignored, because the provider never sees them. hibernate.enable_lazy_load_no_trans. It silences the error by opening a session per access; connection churn and inconsistent reads usually follow.
Official documentation: Hibernate User Guide: association fetching and Spring Framework: Hibernate ORM integration.
Official references
primary documentationThe Java documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Java guides
All Java guidesSpring Boot: No qualifying bean of type available
The context could not satisfy a constructor argument. Scan boundaries, missing stereotypes, ambiguous candidates and test slices are the usual reasons.
Method Scope in Java: How Local Variables Work
Understand how variables behave inside Java methods: local variable boundaries, block scope, parameter scope, shadowing, and lifetime implications.
Java: HikariPool connection is not available, request timed out
The HikariCP pool ran out of connections for the whole connectionTimeout. Read the counters, find leaks or slow queries, then size the pool.
Java: DateTimeParseException: Text could not be parsed
The formatter pattern and the input disagree. Check the index in the message, the locale, and whether the text needs a ZonedDateTime instead.
More in Java
All Java guidesThe guides filed next to this one in Java, in library order.