Skip to lesson

Open Session in View and why to turn it off

ShopLite's order page works in tests, but under load requests time out while the database sits idle. One Spring Boot default keeps connections busy during slow work and hides queries in the web layer.

spring.jpa.open-in-view=true and the startup warning

Open Session in View (OSIV) keeps the JPA session open until the HTTP response has been written, so lazy links can still load in controllers and views. Spring Boot turns it on by default.

Spring Boot starts with OSIV on and says so in the log. Example 1 is the warning that appears at every start of a web app with JPA.

Example 1 · The startup warning when open-in-view is not set

Runs in: the perf-lab practice project (Spring Boot 4.1, ShopLite database)

YAML
# application.yml of perf-lab: spring.jpa.open-in-view is NOT set, so Spring Boot's default (true) appliesspring:  main:    web-application-type: servlet# terminaljava -jar target/perf-lab-0.0.1-SNAPSHOT.jar
Sample output
WARN  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 warning

What this code does

  • Spring Boot logs this at WARN level on every start of a web app with JPA when the property is missing. It is not an error; the app runs with OSIV on.
  • Writing spring.jpa.open-in-view with any value removes the warning. ShopLite writes false.

The property spring.jpa.open-in-view registers OpenEntityManagerInViewInterceptor, which opens an EntityManager when a request arrives and closes it only after the response is written. Without it, the session lives only as long as the service's @Transactional method.

Spring Boot sets the property to true unless you set it yourself, and then logs the warning of Example 1 at every start. The warning disappears as soon as the property is written explicitly, true or false; it is there because the default is convenient for beginners and costly for real apps. ShopLite sets spring.jpa.open-in-view=false in the shared application.yml, so every profile has it off. The rest of this lesson shows why.

How it hides LazyInitializationException and moves queries into the web layer

LazyInitializationException is thrown when code reads a lazy link after its session has closed, because the proxy can no longer load its row.

With OSIV on, a lazy getter still works after the service has returned. Example 2 shows the controller running a SELECT after the service is done.

Example 2 · OSIV on: the controller's lazy getter runs SQL after the service

Runs in: the perf-lab practice project (Spring Boot 4.1, ShopLite database)

Java
// OrderLookupService.java (fragment): returns the entity/** Returns the entity: the caller may touch lazy links after the transaction ended. */public Order findOrder(Integer id) {    return orders.findById(id).orElseThrow();}
// OrderLabController.java (fragment): the controller reads a lazy link/** Anti-pattern: the controller walks a lazy link of an entity. */@GetMapping("/lab/orders/{id}")OrderView entityInController(@PathVariable Integer id) {    Order order = service.findOrder(id);    System.out.println(">>> service returned, transaction is over");    return new OrderView(order.getId(), order.getCustomer().getFullName(), order.getStatus().name());}
Sample output
$ curl http://localhost:8080/lab/orders/14
{"id":14,"customerName":"Ravi Kumar","status":"SHIPPED"}

(server log)
DEBUG SQL - select o1_0.order_id,o1_0.address_id,o1_0.customer_id,o1_0.ordered_at,o1_0.status from orders o1_0 where o1_0.order_id=?
>>> service returned, transaction is over
DEBUG 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=?

What this code does

  • The order SELECT ran inside the service. The customer SELECT ran after ">>> service returned", in the controller, outside the transaction, because OSIV kept the session open.
  • The response looks right, so the extra query and the layering problem stay invisible until someone reads the log.

The session is still open, so the proxy loads its row: in Example 2 the log shows the SQL after the line "service returned", although the service's transaction is over. That looks friendly but hides two problems. The query runs outside any transaction, in auto-commit mode, after the service thought it was done. And the controller, a mapper or Jackson can now trigger N+1 in the web layer, where nobody planned or counted the queries; the Jackson example of the N+1 lesson only "worked" because OSIV was on.

Without OSIV the same code fails with LazyInitializationException. That exception is not the bug; it is the signal that the service did not load what the response needs.

A connection held for the whole request: pool exhaustion

Pool exhaustion is the state in which every connection of the pool is in use, so new requests wait and finally fail with a timeout.

Connections are limited, so holding one while waiting wastes it. Example 3 runs four slow requests against a pool of two.

A request has three parts: the service query, a slow call that takes about 3 seconds, and writing the JSON response. With Open Session in View on, the database connection is held for all three parts.

Example 3 · OSIV on: four slow requests and a pool of two

Runs in: the perf-lab practice project (Spring Boot 4.1, ShopLite database)

Java
// OrderLabController.java (fragment)/** The same, plus a slow call (a courier tracking API) after the data is loaded. */@GetMapping("/lab/orders/{id}/tracking")OrderView slowEntity(@PathVariable Integer id) throws InterruptedException {    Order order = service.findOrder(id);    String name = order.getCustomer().getFullName();    Thread.sleep(3000);                                   // waiting for the courier API    return new OrderView(order.getId(), name, order.getStatus().name());}
# terminal: a tiny pool so the effect is easy to seejava -jar target/perf-lab-0.0.1-SNAPSHOT.jar --spring.datasource.hikari.maximum-pool-size=2 --spring.datasource.hikari.connection-timeout=1000
Sample output
$ for id in 1 2 3 4; do (echo "order $id: $(curl -s -w ' HTTP %{http_code} in %{time_total}s' http://localhost:8080/lab/orders/$id/tracking)") & done; wait
order 2: {"timestamp":"2026-10-16T06:56:48.256Z","status":500,"error":"Internal Server Error","path":"/lab/orders/2/tracking"} HTTP 500 in 1.040091s
order 4: {"timestamp":"2026-10-16T06:56:48.256Z","status":500,"error":"Internal Server Error","path":"/lab/orders/4/tracking"} HTTP 500 in 1.026163s
order 1: {"id":1,"customerName":"Asha Rao","status":"DELIVERED"} HTTP 200 in 3.036701s
order 3: {"id":3,"customerName":"Asha Rao","status":"DELIVERED"} HTTP 200 in 3.024171s

(server log)
DEBUG SQL - select o1_0.order_id,o1_0.address_id,o1_0.customer_id,o1_0.ordered_at,o1_0.status from orders o1_0 where o1_0.order_id=?
DEBUG 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=?
DEBUG SQL - select o1_0.order_id,o1_0.address_id,o1_0.customer_id,o1_0.ordered_at,o1_0.status from orders o1_0 where o1_0.order_id=?
DEBUG 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=?
WARN  error - HHH000247: ErrorCode: 0, SQLState: null
WARN  error - HikariPool-1 - Connection is not available, request timed out after 1003ms (total=2, active=2, idle=0, waiting=1)
WARN  error - HHH000247: ErrorCode: 0, SQLState: null
WARN  error - HikariPool-1 - Connection is not available, request timed out after 1002ms (total=2, active=2, idle=0, waiting=0)
ERROR [dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction] with root cause
java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 1002ms (total=2, active=2, idle=0, waiting=0)
ERROR [dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction] with root cause
java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 1003ms (total=2, active=2, idle=0, waiting=1)

What this code does

  • Requests 1 and 3 took the two connections and kept them through their 3-second wait. Requests 2 and 4 waited 1 second for a connection and failed with SQLTransientConnectionException.
  • Hikari's own message tells the story: total=2, active=2, idle=0. Both connections were busy doing nothing but waiting.

With OSIV on, the request's session keeps the JDBC connection it used until the response is finished. A connection pool such as HikariCP has a fixed number of connections (10 by default). If a request loads its data and then waits for something slow, such as a courier tracking API, a PDF or a big JSON response, the connection waits with it and no other request can use it. In Example 3 two requests got a connection; the other two waited the full connection-timeout (1 second) and failed with "Connection is not available, request timed out". The database was idle the whole time: it was the waiting, not the SQL, that used the pool up.

On a real server this shows up as rising response times and timeouts under load, while the database's CPU looks fine. The arithmetic in Practice 6 shows how quickly holding a connection 300 ms instead of 20 ms caps a pool of 10.

Predict the output

How many requests succeed?

Four requests arrive together. Each waits 3 seconds after its query.

Round 1 of 3

OSIV is on, the pool has 2 connections and the timeout is 1 second.

hikari.maximum-pool-size: 2
hikari.connection-timeout: 1000
spring.jpa.open-in-view: true

Turning it off: what breaks and how DTO mapping fixes it

spring.jpa.open-in-view is the Spring Boot property that switches Open Session in View on or off. Its default is true, with a startup warning; ShopLite sets it to false.

Turning OSIV off is one line, and it exposes the hidden work. Example 4 shows the new exception, and Example 5 the fixed endpoint.

Example 4 · OSIV off: the hidden query becomes LazyInitializationException

Runs in: the perf-lab practice project (Spring Boot 4.1, ShopLite database)

YAML
# application.ymlspring:  jpa:    open-in-view: false// the same OrderLabController.entityInController(...) as in Example 2
Sample output
$ curl -i http://localhost:8080/lab/orders/14
HTTP/1.1 500
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 06:58:09 GMT
Connection: close

{"timestamp":"2026-10-16T06:58:09.359Z","status":500,"error":"Internal Server Error","path":"/lab/orders/14"}

(server log)
DEBUG SQL - select o1_0.order_id,o1_0.address_id,o1_0.customer_id,o1_0.ordered_at,o1_0.status from orders o1_0 where o1_0.order_id=?
>>> service returned, transaction is over
ERROR [dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.hibernate.LazyInitializationException: Could not initialize proxy [com.shoplite.lab.customer.Customer#2] - no session] with root cause
org.hibernate.LazyInitializationException: Could not initialize proxy [com.shoplite.lab.customer.Customer#2] - no session

What this code does

  • The order loads inside the service. In the controller the customer proxy has no session any more, so getFullName() throws Could not initialize proxy [com.shoplite.lab.customer.Customer#2] - no session.
  • The startup warning is gone too. This failure is what you want in development: it points at the exact line that read a lazy link outside the service.

Example 5 · OSIV off with a DTO from the service: four slow requests, all fine

Runs in: the perf-lab practice project (Spring Boot 4.1, ShopLite database)

Java
// OrderLookupService.java (fragment): the DTO is built inside the transaction/** Builds the response inside the transaction: nothing lazy leaves this method. */public OrderView findOrderView(Integer id) {    Order order = orders.findById(id).orElseThrow();    return new OrderView(order.getId(), order.getCustomer().getFullName(), order.getStatus().name());}
// OrderLabController.java (fragment): the same slow courier call, but no entity/** The fix: the service returns a DTO; the controller never sees an entity. */@GetMapping("/lab/order-views/{id}")OrderView dto(@PathVariable Integer id) throws InterruptedException {    OrderView view = service.findOrderView(id);    Thread.sleep(3000);                                   // the same slow courier call    return view;}
# terminaljava -jar target/perf-lab-0.0.1-SNAPSHOT.jar --spring.jpa.open-in-view=false --spring.datasource.hikari.maximum-pool-size=2 --spring.datasource.hikari.connection-timeout=1000
Sample output
$ for id in 1 2 3 4; do (echo "order $id: $(curl -s -w ' HTTP %{http_code} in %{time_total}s' http://localhost:8080/lab/order-views/$id)") & done; wait
order 1: {"id":1,"customerName":"Asha Rao","status":"DELIVERED"} HTTP 200 in 3.149466s
order 2: {"id":2,"customerName":"Ravi Kumar","status":"DELIVERED"} HTTP 200 in 3.049883s
order 4: {"id":4,"customerName":"Meena Iyer","status":"CANCELLED"} HTTP 200 in 3.035375s
order 3: {"id":3,"customerName":"Asha Rao","status":"DELIVERED"} HTTP 200 in 3.043355s

What this code does

  • The service loads the order and customer and builds OrderView inside its transaction; the connection returns to the pool before the 3-second courier call.
  • With the same pool of 2, all four requests get 200 in about 3 seconds each, because each one needs a connection only for a few milliseconds.

The warning goes away, the session closes when the service's transaction ends, and the connection goes back to the pool right after the last query. What breaks is exactly the hidden work: every controller, mapper or JSON response that read a lazy link now throws LazyInitializationException (Example 4). Do not "fix" it by turning OSIV back on or making links EAGER. Fix each place by building the response inside the service: map entities to records within the @Transactional method, or use a DTO query, with a fetch join or entity graph if entities are needed. In Example 5 the service returns an OrderView record, the connection is released before the 3-second wait, and all four requests succeed with a pool of 2.

To turn it off in an existing app:

  1. Set spring.jpa.open-in-view=false in the shared application.properties (or application.yml).
  2. Start the app and call every endpoint, or run the integration tests.
  3. For each LazyInitializationException, find the lazy getter outside the service.
  4. Move the mapping into the service method, or fetch the link in its query.
  5. Check the SQL log: the queries now run inside the service, and the count is what you expect.

Order of execution

Follow one request

With OSIV off, put the life of the connection in order.

Next step

Check your understanding

11 quick questions