Spring MVC Open Session in View Explained With Examples
What Open Session in View does in Spring Boot, why it hides LazyInitializationException, how it keeps a database connection longer, and how to spot its costs.

The first time a Spring Boot application starts with Spring Data JPA, it prints a warning that most developers scroll past: 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 warning. The warning is accurate and under explained. Open Session in View is a feature, an interceptor registered by default, that changes where lazy loading works and how long connections are held. It is the reason a fresh tutorial application never shows LazyInitializationException, and the reason a production service sometimes runs out of connections for no obvious reason. This post explains what it does, shows the behaviour with and without it, lists the costs and gives the diagnostic steps. The decision to turn it off, and how, is in disabling Open Session in View safely.
The problem it solves
JPA entities have lazy associations: loading an Order does not load its lines until something touches the collection. Touching it needs an open persistence context (the EntityManager, Hibernate's Session). Normally the persistence context lives as long as the transaction, which ends when the @Transactional service method returns. If the controller then reads the lazy collection, there is no open session, and Hibernate throws:
@Service
public class OrderService {
@Transactional(readOnly = true)
public Order find(long id) {
return orders.findById(id).orElseThrow(); // lines is a lazy collection, not loaded
}
}
@RestController
public class OrderController {
@GetMapping("/orders/{id}")
public OrderDto get(@PathVariable long id) {
Order order = service.find(id); // the transaction has ended here
return OrderDto.from(order); // touches order.getLines()
}
}org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: dev.javahacks.orders.Order.lines: could not initialize proxy - no SessionThat error is the system working as designed: you tried to read data outside the unit of work that loaded it. Fixes are to load what you need inside the service (a fetch join, an entity graph, a DTO projection), covered in fixing LazyInitializationException in Spring Boot. Open Session in View is the other fix: make the session outlive the transaction.
What the interceptor does
Spring Boot registers OpenEntityManagerInViewInterceptor for web applications when JPA is present and the property is not set to false. It runs around the handler:
- Before the controller: creates an
EntityManagerand binds it to the thread, without starting a transaction. - During the request: when a
@Transactionalmethod runs, it joins the already boundEntityManagerinstead of opening a new one, and begins its transaction on it. - When the transactional method returns: the transaction commits, but the
EntityManagerstays open and bound. - After the response is complete (after view rendering or JSON serialisation): the interceptor closes the
EntityManager.
So the session now spans the whole request. In the example above, OrderDto.from(order) touches order.getLines() while the session is still open, Hibernate loads the collection with a fresh query, and no exception occurs. The code looks fine and works.
You can watch it with SQL logging:
spring.jpa.show-sql=true
logging.level.org.springframework.orm.jpa=DEBUGDEBUG o.s.o.j.JpaTransactionManager : Creating new transaction with name [OrderService.find]
select o1_0.id,o1_0.status from orders o1_0 where o1_0.id=?
DEBUG o.s.o.j.JpaTransactionManager : Committing JPA transaction on EntityManager [SessionImpl(...)]
select l1_0.order_id,l1_0.id,l1_0.sku from order_line l1_0 where l1_0.order_id=?Look at the order: the second select appears after the commit, which means a query ran outside any transaction, during DTO mapping in the controller. That is Open Session in View at work, and also the first hint of its costs.
Cost 1: hidden queries and N plus 1
Because lazy loading works everywhere, the code that triggers queries can be anywhere: a controller, a mapper, a Jackson serialiser walking an entity graph, a Thymeleaf template calling order.customer.name. None of those sites looks like data access, and none is reviewed as such. A list endpoint that returns 100 orders and touches order.getCustomer() on each issues 101 queries, and the code gives no sign.
@GetMapping("/orders")
public List<OrderDto> list() {
return service.findAll().stream()
.map(o -> new OrderDto(o.getId(), o.getCustomer().getName())) // 1 query per order
.toList();
}The N plus 1 problem exists with or without the interceptor; with it off, the exception forces you to fetch the data deliberately, and with it on, the problem is silent. The detection and fixes are in detecting N plus 1 queries in tests.
Cost 2: connections held longer
The second cost is operational. After a transaction commits, Hibernate normally releases the JDBC connection. With a long lived EntityManager, Spring's Hibernate integration holds the connection once acquired: the vendor adapter sets Hibernate's connection handling mode to delay acquisition and hold until the session closes. So with Open Session in View, a request that touches the database once keeps its connection checked out until the response has been fully written.
request starts ──► first query ──► (connection acquired) ──► serialise JSON ──► write to a slow client ──► response done
│ │
└──────────────── connection held the whole time ───────────────────┘The window is as long as the slowest step after the query. Rendering a large page, serialising a big graph or writing to a client on a slow network all extend it. With a pool of ten connections, ten slow downloads use the entire pool, and the next request waits for a connection that the database is not even using. This shows in the metrics as hikaricp.connections.active at the maximum with low database activity, and in the logs as Connection is not available, request timed out after 30000ms, the pattern analysed in connection pool exhaustion. The connection pool needs the interceptor off to be accurate: with it off, a connection is held only during the transaction.
Cost 3: blurred transaction boundaries
The transaction covers only the service method, but the session spans more, so the code outside the transaction sees data that is not guaranteed consistent. Lazy loads after the commit run in autocommit mode: each is its own statement against a database that other transactions are changing. Two lazy loads in the same controller can see different states of the world. For read only display that rarely matters; for logic that depends on a consistent view, such as computing a total from lines loaded lazily, it is a latent bug. Code written to expect the transaction to define what is consistent loses that guarantee, and the failure is rare enough to escape testing.
There is a related trap with writes. An entity modified outside a transaction while the session is open is not saved by Spring, because there is no commit to flush it, but a later @Transactional call in the same request that flushes the session will write the change. The order in which code runs then decides what is persisted, which is surprising.
Cost 4: it papers over design
The deepest cost is cultural. Developers learn that lazy loading works anywhere, so entities leak into controllers and templates, DTOs are skipped and the persistence model becomes the API model. The first time the application grows a second consumer, an event, a scheduled job or a message listener, none of which has an Open Session in View, the exceptions appear all at once. A service layer that returns complete, self sufficient results, DTOs or fully fetched aggregates, behaves the same everywhere.
When it is acceptable
It is a default with reasons. For a small server rendered application with a template per page, a handful of users and entities that are read and rarely written, the interceptor is convenient and the risks are small. Prototypes and tutorials benefit. If you keep it, keep the costs in view: put an alert on connection pool wait time, test list endpoints for query counts and cap response sizes. For any service handling real traffic, an API consumed by mobile clients, or code that will be consumed by more than the web layer, turn it off.
Detecting its presence and effects
Check what the application is using:
spring.jpa.open-in-view=true # explicit
# absent: defaults to true in Spring Boot, with the startup warningSearch the logs for the warning at startup. To find out which requests depend on it, switch it off in a test profile and run the suite: every LazyInitializationException is a place where data is read outside a transaction.
@SpringBootTest(properties = "spring.jpa.open-in-view=false")
class NoOsivSmokeTest {
@Autowired MockMvc mvc;
@Test
void ordersEndpointDoesNotNeedAnOpenSession() throws Exception {
mvc.perform(get("/orders/1")).andExpect(status().isOk());
}
}Count queries per request with Hibernate statistics, as in logging SQL and counting statements, and compare the numbers with and without the interceptor to see how many lazy loads happen outside your service layer.
When this does not apply
Reactive applications do not use the servlet interceptor, and R2DBC has no lazy loading, so the question does not arise. Applications using Spring Data JDBC have no persistence context and no lazy association proxies. Applications that fetch everything explicitly in services and map to DTOs there are unaffected by the setting in behaviour and benefit from turning it off in connection usage. The interceptor's own Javadoc is clear about its trade-offs: see the OpenEntityManagerInViewInterceptor documentation and the Spring Boot reference on the property.


