LazyInitializationException and why it happens
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A controller returns an order and the client gets a 500: "could not initialize proxy - no session". The same code works inside the service. What changed between the two places?
Lazy proxies and collections need an open persistence context
A lazy association is a link between entities that Hibernate loads only when you first use it. Until then the field holds a proxy (for a single link) or a collection object that has not run its SELECT yet.
The listing loads a product and an order inside a transaction, then touches their lazy links: a proxy for the category and a collection of items.
Example 1 · A lazy proxy and a lazy collection at work
Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/LazyProxyDemo.javapackage com.shoplite.lab;
import org.hibernate.Hibernate;import org.springframework.stereotype.Component;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.category.Category;import com.shoplite.order.Order;import com.shoplite.order.OrderRepository;import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
@Component("lazy-proxy")public class LazyProxyDemo implements LabDemo {
private final ProductRepository products; private final OrderRepository orders;
public LazyProxyDemo(ProductRepository products, OrderRepository orders) { this.products = products; this.orders = orders; }
@Override @Transactional(readOnly = true) public void run() { Product phone = products.findById(1).orElseThrow(); Category category = phone.getCategory(); System.out.println("category is a proxy: " + (category.getClass() != Category.class)); System.out.println("initialized? " + Hibernate.isInitialized(category) + ", id=" + category.getId()); System.out.println("name: " + category.getName()); System.out.println("initialized? " + Hibernate.isInitialized(category));
Order order = orders.findById(14).orElseThrow(); System.out.println("order loaded, items not touched yet"); System.out.println("item count: " + order.getItems().size()); }}$ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=lazy-proxy" DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? category is a proxy: true initialized? false, id=2 DEBUG org.hibernate.SQL : select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=? name: Mobiles initialized? true DEBUG org.hibernate.SQL : select o1_0.order_id,o1_0.customer_id,o1_0.address_id,o1_0.ordered_at,o1_0.status from orders o1_0 where o1_0.order_id=? order loaded, items not touched yet DEBUG org.hibernate.SQL : select i1_0.order_id,i1_0.order_item_id,i1_0.product_id,i1_0.quantity,i1_0.unit_price from order_items i1_0 where i1_0.order_id=? item count: 2
What this code does
- Loading product 1 selects only the products row.
getCategory()returns a proxy (a generated subclass, notCategoryitself) that is not initialized;getId()answers 2 without SQL. getName()needs real data, so the proxy runs the categories SELECT right then. The order's items load the same way, atsize().- Both lazy loads worked because they happened inside the
@Transactionalmethod, while the persistence context was open.
A lazy @ManyToOne such as Product.category holds a proxy: a generated subclass of Category that knows only the id. The first call that needs real data, like getName(), makes the proxy run a SELECT. A lazy collection such as Order.items runs its SELECT on first use, like size() or a loop.
Loading a product should not drag in its category, the category's parent and so on, so ShopLite maps every link as LAZY. The catch: the proxy loads through the persistence context it came from. getId() is free, because the id is already inside the proxy; anything else needs that context to be still open.
Reproducing "could not initialize proxy - no session"
LazyInitializationException is thrown when code touches a lazy association after the persistence context that could load it has closed. In a Spring Boot app it usually means an entity left the transactional service.
A read-only service method returns an order entity, and the caller then reads its items. The listing shows the exception and its log.
Example 2 · The service returns an entity: LazyInitializationException
Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/OrderLookupService.javapackage com.shoplite.lab;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.order.Order;import com.shoplite.order.OrderRepository;
@Servicepublic class OrderLookupService {
private final OrderRepository orders;
public OrderLookupService(OrderRepository orders) { this.orders = orders; }
// The mistake: the entity leaves the service, the transaction (and its session) ends here @Transactional(readOnly = true) public Order findOrder(int id) { return orders.findById(id).orElseThrow(); }}
// src/main/java/com/shoplite/lab/LazyExceptionDemo.javapackage com.shoplite.lab;
import org.springframework.stereotype.Component;
import com.shoplite.order.Order;
@Component("lazy-exception")public class LazyExceptionDemo implements LabDemo {
private final OrderLookupService service;
public LazyExceptionDemo(OrderLookupService service) { this.service = service; }
@Override public void run() { Order order = service.findOrder(14); System.out.println("order " + order.getId() + " is " + order.getStatus());
try { System.out.println("items: " + order.getItems().size()); } catch (RuntimeException e) { System.out.println(e.getClass().getName()); System.out.println(" " + e.getMessage()); }
try { System.out.println("customer: " + order.getCustomer().getFullName()); } catch (RuntimeException e) { System.out.println(e.getClass().getName()); System.out.println(" " + e.getMessage()); } }}$ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=lazy-exception" DEBUG org.hibernate.SQL : select o1_0.order_id,o1_0.customer_id,o1_0.address_id,o1_0.ordered_at,o1_0.status from orders o1_0 where o1_0.order_id=? order 14 is SHIPPED org.hibernate.LazyInitializationException Cannot lazily initialize collection of role 'com.shoplite.order.Order.items' with key '14' (no session) org.hibernate.LazyInitializationException Could not initialize proxy [com.shoplite.customer.Customer#2] - no session
What this code does
findOrderloaded order 14 and returned it; its transaction, and its persistence context, closed on return.getId()andgetStatus()still work because they are plain columns of the orders row.getItems().size()fails with "Cannot lazily initialize collection of role ... (no session)", andgetCustomer().getFullName()with "Could not initialize proxy [com.shoplite.customer.Customer#2] - no session". These are Hibernate 7's wordings of the classic "could not initialize proxy - no Session".- A controller that returned this
Orderwould fail the same way inside Jackson, and the client would get a 500.
A @Transactional(readOnly = true) method that returns the entity looks harmless, but when it returns, Spring commits and closes the persistence context. The caller gets a detached order whose items and customer were never loaded, and the moment it touches them, Hibernate has no session to load from. In a controller the same thing happens inside Jackson while it writes the JSON, so the client gets a 500.
With spring.jpa.open-in-view=false (ShopLite's setting) the error shows up at once in development, which is what you want. The exception is not a Hibernate bug: it reports a real design problem, an entity escaping the layer that owns the transaction.
Find the bug
Find the late access
A LazyInitializationException is thrown. Tap the line that goes wrong.
The caller reads the items of an order that the service returned.
Round 1 of 3Right fix 1: map to a DTO inside the transaction
Mapping to a DTO inside the transaction means building the response object in the transactional service method, while the persistence context is open, and returning only that DTO. The lazy links load as the mapper reads them.
The listing builds an OrderResponse inside the service, first with plain lazy loading and then with a fetch join.
Example 3 · DTOs built inside the transaction, with and without a fetch join
Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/OrderDetailsService.javapackage com.shoplite.lab;
import java.math.BigDecimal;import java.util.List;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.order.Order;import com.shoplite.order.OrderItem;import com.shoplite.order.OrderRepository;
@Servicepublic class OrderDetailsService {
public record ItemLine(String sku, String productName, int quantity, BigDecimal lineTotal) { }
public record OrderDetails(int id, String status, List<ItemLine> items, BigDecimal total) { }
private final OrderRepository orders;
public OrderDetailsService(OrderRepository orders) { this.orders = orders; }
// Fix 1: map to a DTO while the transaction is still open @Transactional(readOnly = true) public OrderDetails details(int id) { return toDetails(orders.findById(id).orElseThrow()); }
// Fix 2: the same DTO, but one query loads the order, its items and their products @Transactional(readOnly = true) public OrderDetails detailsWithFetchJoin(int id) { return toDetails(orders.findWithItemsById(id).orElseThrow()); }
private OrderDetails toDetails(Order order) { List<ItemLine> lines = order.getItems().stream().map(this::toLine).toList(); return new OrderDetails(order.getId(), order.getStatus().name(), lines, order.total()); }
private ItemLine toLine(OrderItem item) { return new ItemLine(item.getProduct().getSku(), item.getProduct().getName(), item.getQuantity(), item.lineTotal()); }}
@Query(""" select o from Order o join fetch o.items i join fetch i.product where o.id = :id""")Optional<Order> findWithItemsById(@Param("id") Integer id);$ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=order-details" -- fix 1: DTO built inside the transaction DEBUG org.hibernate.SQL : select o1_0.order_id,o1_0.customer_id,o1_0.address_id,o1_0.ordered_at,o1_0.status from orders o1_0 where o1_0.order_id=? DEBUG org.hibernate.SQL : select i1_0.order_id,i1_0.order_item_id,i1_0.product_id,i1_0.quantity,i1_0.unit_price from order_items i1_0 where i1_0.order_id=? DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? order 14 SHIPPED, total 19298.00 ItemLine[sku=MOB-RN13, productName=Redmi Note 13 5G, quantity=1, lineTotal=17999.00] ItemLine[sku=ACC-AD141, productName=boAt Airdopes 141, quantity=1, lineTotal=1299.00] -- fix 2: fetch join, then the DTO DEBUG org.hibernate.SQL : select o1_0.order_id,o1_0.customer_id,o1_0.address_id,i1_0.order_id,i1_0.order_item_id,i1_0.product_id,p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock,i1_0.quantity,i1_0.unit_price,o1_0.ordered_at,o1_0.status from orders o1_0 join order_items i1_0 on o1_0.order_id=i1_0.order_id join products p1_0 on p1_0.product_id=i1_0.product_id where o1_0.order_id=? order 14 SHIPPED, total 19298.00 ItemLine[sku=MOB-RN13, productName=Redmi Note 13 5G, quantity=1, lineTotal=17999.00] ItemLine[sku=ACC-AD141, productName=boAt Airdopes 141, quantity=1, lineTotal=1299.00]
What this code does
detailsmaps the order to records while the transaction is open: no exception, but four SELECTs (order, items, then one per product as the mapper reads it).detailsWithFetchJoinuses the join fetch query: one SELECT with two joins brings the order, both items and both products, and the same mapper reads them with no further SQL.- Both return the same
OrderDetailsrecord. The caller never sees an entity, so nothing outside the service can trigger lazy loading.
The controller receives plain records that need no database, and the JSON shape stays under your control instead of following the table layout. This matches ShopLite's layer rule: entities never leave the service.
The cost shows in the log: one SELECT for the order, one for its items and one per product. That is the N+1 query problem in small. For one order with two items it is fine; for lists it is not, which is what the second fix is for.
Right fix 2: fetch what you need (join fetch, @EntityGraph)
A fetch join loads an association in the same query. In JPQL, join fetch o.items i join fetch i.product returns the order, its items and their products in one SELECT.
The listing loads the order with its items in one SELECT, first with a JPQL join fetch and then with @EntityGraph.
Example 4 · @EntityGraph: the same fetch without JPQL
Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/order/OrderRepository.javapackage com.shoplite.order;
import java.util.Optional;
import org.springframework.data.jpa.repository.EntityGraph;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.data.jpa.repository.Query;import org.springframework.data.repository.query.Param;
public interface OrderRepository extends JpaRepository<Order, Integer> {
@Query(""" select o from Order o join fetch o.items i join fetch i.product where o.id = :id""") Optional<Order> findWithItemsById(@Param("id") Integer id);
@EntityGraph(attributePaths = {"items", "items.product"}) Optional<Order> findDetailedById(Integer id);
@Query("select o from Order o join fetch o.customer where o.id = :id") Optional<Order> findWithCustomerById(@Param("id") Integer id);}
// src/main/java/com/shoplite/lab/EntityGraphDemo.java (its run method)@Override@Transactional(readOnly = true)public void run() { Order order = orders.findDetailedById(16).orElseThrow(); order.getItems().forEach(item -> System.out.println(item.getProduct().getSku() + " x " + item.getQuantity())); System.out.println("total: " + order.total());}$ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=entity-graph" DEBUG org.hibernate.SQL : select o1_0.order_id,o1_0.customer_id,o1_0.address_id,i1_0.order_id,i1_0.order_item_id,i1_0.product_id,p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock,i1_0.quantity,i1_0.unit_price,o1_0.ordered_at,o1_0.status from orders o1_0 left join order_items i1_0 on o1_0.order_id=i1_0.order_id left join products p1_0 on p1_0.product_id=i1_0.product_id where o1_0.order_id=? BK-ATOMIC x 3 FSH-SHOE x 1 total: 3696.00
What this code does
findDetailedByIdis a derived query;@EntityGraph(attributePaths = {"items", "items.product"})tells Hibernate to load those paths in the same SELECT.- The generated SQL uses
left join, while the JPQLjoin fetchused an inner join. An order without items would still be returned here, with an empty list.
Fetching is decided per use case, not on the mapping: the order details endpoint fetches items and products, the order list fetches nothing extra, and the mapping stays LAZY. An @EntityGraph(attributePaths = ...) on a repository method gives the same fetch without writing JPQL.
One difference matters: join fetch is an inner join, so an order with no items would not be found at all, while @EntityGraph uses left joins and still returns the order with an empty list. ShopLite orders always have at least one item, so both work. The Performance traps module covers fetching lists and pagination in depth.
Fix the error
Load the items in the query
Read the error, then pick the line that fetches the items with the order.
Round 1 of 2
The repository query returns an order without its items.
Error
LazyInitializationException: Cannot lazily initialize collection of role 'Order.items': no session
Wrong fixes: EAGER, open-in-view, enable_lazy_load_no_trans
Open Session in View (spring.jpa.open-in-view=true, Spring Boot's default) keeps the persistence context open until the HTTP response is written, so lazy loading also works in controllers and in Jackson.
Three popular "fixes" remove the exception but create worse problems. The log line below is the warning Spring Boot prints when open-in-view is left on.
WARN o.s.b.j.a.JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warningExample 5 · EAGER: queries nobody asked for
Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)
// The wrong fix, in src/main/java/com/shoplite/product/Product.java@ManyToOne(fetch = FetchType.EAGER, optional = false)@JoinColumn(name = "category_id", nullable = false)private Category category;
// src/main/java/com/shoplite/lab/EagerFindAllDemo.javapackage com.shoplite.lab;
import org.springframework.stereotype.Component;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.product.ProductRepository;
@Component("eager-find-all")public class EagerFindAllDemo implements LabDemo {
private final ProductRepository products;
public EagerFindAllDemo(ProductRepository products) { this.products = products; }
@Override @Transactional(readOnly = true) public void run() { // we only want SKUs and stock; the categories are not used at all products.findAll().forEach(p -> System.out.print(p.getSku() + ":" + p.getStock() + " ")); System.out.println(); }}-- with @ManyToOne(fetch = FetchType.LAZY), as ShopLite maps it $ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=eager-find-all" DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 MOB-RN13:40 MOB-GM35:25 MOB-IP15:8 LAP-IPS3:12 LAP-HPV15:5 ACC-AD141:120 ACC-PB20K:60 ACC-M331:0 BK-CLEAN:30 BK-PRAG:22 BK-ATOMIC:50 FSH-KURTA:35 FSH-SHOE:18 HK-COOK3L:15 ACC-USBC1:0 -- after changing Product.category to FetchType.EAGER $ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=eager-find-all" DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 DEBUG org.hibernate.SQL : select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=? DEBUG org.hibernate.SQL : select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=? DEBUG org.hibernate.SQL : select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=? DEBUG org.hibernate.SQL : select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=? DEBUG org.hibernate.SQL : select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=? DEBUG org.hibernate.SQL : select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=? MOB-RN13:40 MOB-GM35:25 MOB-IP15:8 LAP-IPS3:12 LAP-HPV15:5 ACC-AD141:120 ACC-PB20K:60 ACC-M331:0 BK-CLEAN:30 BK-PRAG:22 BK-ATOMIC:50 FSH-KURTA:35 FSH-SHOE:18 HK-COOK3L:15 ACC-USBC1:0
What this code does
- With LAZY, listing SKUs and stock is one SELECT. With EAGER, Hibernate loads every product's category right away: one extra SELECT for each of the 6 categories used, although the demo never reads a category.
- With 500 categories that is 500 extra queries on every product list. EAGER cannot be switched off per query, while a fetch join or entity graph can be switched on per query.
Example 6 · enable_lazy_load_no_trans hides the error
Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)
// The same LazyExceptionDemo as Example 2, started with one more property@Overridepublic void run() { // like a controller: no transaction here Order order = service.findOrder(14); System.out.println("order " + order.getId() + " is " + order.getStatus());
try { System.out.println("items: " + order.getItems().size()); } catch (RuntimeException e) { System.out.println(e.getClass().getName()); System.out.println(" " + e.getMessage()); }
try { System.out.println("customer: " + order.getCustomer().getFullName()); } catch (RuntimeException e) { System.out.println(e.getClass().getName()); System.out.println(" " + e.getMessage()); }}$ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=lazy-exception --spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true" DEBUG org.hibernate.SQL : select o1_0.order_id,o1_0.customer_id,o1_0.address_id,o1_0.ordered_at,o1_0.status from orders o1_0 where o1_0.order_id=? order 14 is SHIPPED DEBUG org.hibernate.SQL : select i1_0.order_id,i1_0.order_item_id,i1_0.product_id,i1_0.quantity,i1_0.unit_price from order_items i1_0 where i1_0.order_id=? items: 2 DEBUG org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id=? customer: Ravi Kumar
What this code does
- No exception now: each lazy access outside the transaction opened a temporary session and ran its own SELECT (items, then customer).
- Every such access is a separate connection and query that no service planned, outside any transaction. In a loop over 50 orders that is 100 hidden queries. Fix the design (Examples 3 and 4) instead.
Each wrong fix has a cost:
FetchType.EAGER: the link is loaded every time, even when nobody uses it.findAll()on products then runs one extra SELECT per category, on every list, forever.- Open Session in View: each lazy access is a hidden query outside the service, and the database connection is held for the whole request.
hibernate.enable_lazy_load_no_trans=true: every lazy access outside a transaction opens a temporary session and runs a query. The error disappears, the queries multiply and data is read outside any transaction.
ShopLite keeps every link LAZY, sets open-in-view to false and builds DTOs in services.
Next step
Check your understanding
12 quick questions