Scrivio Interview library
DebuggingFoundations6 min read · updated 12 November 2026

A controller returns an Order entity and Jackson serialization fails with LazyInitializationException: could not initialize proxy - no Session. Open session in view is disabled. Explain the cause and the proper fixes.

The service method's transaction has ended, so the Order the controller returns is detached, and when Jackson calls a getter on a lazy association there is no session left to load it, hence could not initialize proxy - no Session. The proper fixes are to fetch what the response needs inside the transaction, with a fetch join or entity graph, and better, to map to a DTO inside the service so the controller never sees entities. Switching to EAGER or enabling hibernate.enable_lazy_load_no_trans only hides the problem and costs extra queries.

Why this question is asked

This exception is often the first thing a Spring developer meets after disabling open session in view, the setting that keeps the database session open while the response is written. Everything worked before, the change was recommended by a startup warning, and now the endpoints fail. Interviewers ask about it because the right fix says a lot about how we structure layers. In this answer, we will see where the session ends, reproduce the failure, fix it by fetching inside the transaction, fix it properly with a DTO, and explain why the tempting shortcuts are wrong.

1Where the Session Ends

With @Transactional on a service method, Spring opens a transaction and a persistence context, the session that tracks loaded entities and can run queries, when the method starts, and closes both when it returns. Entities that leave the method are detached: they still hold the data already loaded, but they can no longer load anything else.

A lazy association, such as Order.customer or Order.lines, is a proxy or a collection wrapper that loads its data on first access through the session. If the first access happens after the session is closed, there is nothing to load it with, and Hibernate throws LazyInitializationException. With open session in view enabled, Spring would keep the session open until the response was written, so the access in Jackson succeeded. With it disabled, as here, the session closes when the service returns.

Step throughReturning an entity with OSIV disabled
ControllerOrderServiceHibernate sessionJackson
getOrder(7)
open transaction, find order 7
Order with lazy lines
commit, close session
detached Order
serialize Order
getLines(): no session
LazyInitializationException

8 messages in order. Play them, or step through them one at a time.

2Reproducing the Failure

The code is ordinary, which is why the failure surprises people.

Java
@Service
class OrderService {
@Transactional(readOnly = true)
public Order getOrder(Long id) {
return orderRepository.findById(id).orElseThrow(); // lines and customer not loaded
}
}
@RestController
class OrderController {
@GetMapping("/orders/{id}")
Order get(@PathVariable Long id) {
return orderService.getOrder(id); // Jackson serializes after the service returned
}
}
// GET /orders/7 ->
// HttpMessageNotWritableException ... LazyInitializationException:
// could not initialize proxy - no Session (or: failed to lazily initialize a collection)

The order's own columns serialize fine. The failure comes when Jackson reaches getCustomer().getName() or getLines(), the first lazy access after the session closed.

3Fix 1: Fetch What the Response Needs in the Transaction

If the response needs the lines and the customer, the service should load them while the session is open, with a fetch join or an entity graph.

Java
interface OrderRepository extends JpaRepository<Order, Long> {
@EntityGraph(attributePaths = {"lines", "customer"})
Optional<Order> findDetailedById(Long id);
}
@Transactional(readOnly = true)
public Order getOrder(Long id) {
return orderRepository.findDetailedById(id).orElseThrow(); // 1 query, lines and customer loaded
}

Now Jackson finds the associations already initialized and the exception is gone. This fixes the immediate failure, but Jackson still serializes the entity as it is, so any other lazy association, such as lines.product, fails in the same way, and a bidirectional association from OrderLine back to Order makes the serializer loop. Fetching fixes the data; it does not fix the design.

4Fix 2: Map to a DTO Inside the Service

The better fix is to stop returning entities from the service. The service builds a DTO, a plain object shaped for the response, while the session is open, and returns that.

Java
public record OrderView(Long id, String customerName, BigDecimal total, List<LineView> lines) { }
public record LineView(String sku, int quantity, BigDecimal price) { }
@Transactional(readOnly = true)
public OrderView getOrder(Long id) {
Order o = orderRepository.findDetailedById(id).orElseThrow();
return new OrderView(o.getId(), o.getCustomer().getName(), o.getTotal(),
o.getLines().stream().map(l -> new LineView(l.getSku(), l.getQuantity(), l.getPrice())).toList());
}
@GetMapping("/orders/{id}")
OrderView get(@PathVariable Long id) { return orderService.getOrder(id); }
// {"id":7,"customerName":"Asha Rao","total":42.50,"lines":[{"sku":"BOOK-1","quantity":1,"price":20.00}, ...]}

Notice what changed. All lazy access happens inside the transaction, so it cannot fail later. The JSON shape is explicit and stable, so renaming an entity field no longer changes the API. And internal fields, such as a version column, an internal cost price or a customer's other data, are not exposed by accident. For read-only screens, a DTO projection query that selects these columns directly is even cheaper.

5Fixes to Avoid

Switching the associations to FetchType.EAGER makes this endpoint work by loading lines and customer for every load of Order everywhere in the application, including queries that never need them, often with extra selects. It trades one visible error for many hidden queries.

Enabling hibernate.enable_lazy_load_no_trans lets a detached proxy open a temporary session and a new connection for each lazy access. Serializing an order with 50 lines and their products may then open dozens of short sessions, each with its own query and outside any transaction, so the data can be inconsistent. It is widely considered an anti-pattern. Re-enabling open session in view has a similar effect at the request level: the queries still happen during serialization, as N+1, and the connection is held for the whole request.

Adding the Jackson Hibernate module, which writes uninitialized associations as null, avoids the exception, but the client then gets incomplete data without any sign that something was left out. All these shortcuts hide where data is loaded instead of making it explicit.

Fixes compared
FixException gone?Cost
Fetch join or entity graphyesentity still exposed, other lazy paths may fail
DTO built in the serviceyesa little mapping code, stable API
FetchType.EAGERyesextra queries everywhere the entity loads
enable_lazy_load_no_transyesnew session per lazy access, no consistency
Open session in view againyesN+1 during rendering, long-held connections

6Follow-up questions

Is returning entities from controllers ever acceptable?

For a tiny internal tool, perhaps, but it couples the API to the persistence model, risks exposing internal fields, and makes serialization trigger database access. A record per response is cheap to write and avoids all three, so it is the safer default.

Where should the mapping to DTOs happen?

Inside the transactional service method, or in the repository with a projection query. If the mapping happens in the controller, it runs after the session closed and hits the same exception.

How do I find all the places that relied on OSIV?

Disable it in a test profile and run the integration tests that call real endpoints; each LazyInitializationException points at one. In production, rolling out per service with good error monitoring shows the remaining ones quickly.

7Conclusion

In this answer, we saw that with open session in view disabled the session ends when the service returns, so Jackson's access to a lazy association on the detached Order fails with LazyInitializationException. Fetching the needed associations in the transaction fixes the failure, and mapping to a DTO inside the service fixes the design, while EAGER, enable_lazy_load_no_trans, OSIV and the Jackson module only hide the problem.

What to say in the interviewAbout 90 seconds aloud

Open with

The service method is transactional, so the persistence context closes when it returns. The Order it returns is then detached, and its lazy associations, customer and lines, are still proxies or uninitialized collections.

Then, if they want more

With open session in view disabled, nothing keeps a session open while the response is written, so when Jackson calls getLines or getCustomer().getName(), Hibernate has no session to load them with and throws could not initialize proxy - no Session.

To fix it properly, I would first load what the response needs inside the transaction, with a fetch join or an @EntityGraph on a method like findDetailedById, so it is one query.

But I would go further and map to a DTO inside the service, for example an OrderView record with the customer name and line views, so all lazy access happens while the session is open, the controller never sees entities, the JSON shape is explicit, and internal fields are not exposed. For read-only views, a projection query is even cheaper.

I would not fix it with FetchType.EAGER, which loads those associations everywhere, or hibernate.enable_lazy_load_no_trans, which opens a new session and connection for every lazy access outside any transaction, or by turning OSIV back on, which just moves the N+1 into serialization. Those hide the data access instead of making it explicit.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A controller returns an Order entity and Jackson serialization fails with...": https://scrivio-interview-library.netlify.app/databases/jpa-performance/10679cc558/