Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readJava
#java#hibernate#jpa#spring-boot
Hibernate proxy crate unlocked after its session gate closed with a fetch join bridge

Introduction & Quick Summary

An endpoint that reads a collection returns 500 and logs this:

code
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:

java
// 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=true

The 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.

java
@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:

java
@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 throwsWhyFix
Controller after service returnstransaction endedfetch in the query or return a DTO
Jackson serializing an entityserializer walks lazy fieldsDTO or @JsonIgnore on the back-reference
@Async methodnew thread, no sessionpass loaded data or re-open a transaction
Template rendering (Thymeleaf)view runs after commitOSIV, or load what the view needs
equals/hashCode during a Set insertproxy initialized implicitlycompare ids, not fields
Test after em.clear()detached entityassert inside the transaction
Fetch approachQuery costPagination safeUse when
join fetchone queryno, for collectionsa single aggregate root
@EntityGraphone querydepends on shaperepository methods
@BatchSize / default_batch_fetch_size1 + n/k queriesyeslists of entities
DTO projectionone query, exact columnsyesread endpoints
EAGER everywhereunpredictable joinsnoalmost never
SettingDefaultEffect
spring.jpa.open-in-viewtruesession spans the request; hides the bug
hibernate.default_batch_fetch_sizeunsetbatches lazy loads by id
@Transactional(readOnly = true)—still a session, still ends at return
hibernate.enable_lazy_load_no_transfalseopens 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:

java
@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:

java
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:

java
@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: false

Disabling 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:

java
// 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:

java
@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:

java
@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.
  • getReferenceById versus findById. The reference is a proxy; reading a lazy field outside the transaction throws exactly this error.
  • Lombok @Data on entities. Generated toString, equals and hashCode touch every field, including lazy ones, and can trigger loads in logs.
  • Spring Boot 3 and Jakarta imports. Mixing javax.persistence with jakarta.persistence annotations 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 documentation

The Java documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.