Video in progress

How does `spring.jpa.open-in-view` being enabled affect the connection pool, and why is it recommended to turn it off?

Open Session in View keeps the Hibernate session open for the whole HTTP request. After the first lazy load, the JDBC connection stays busy until the view is rendered and the response is sent. With a slow client or an external call, the pool runs out quickly.

📖 Answer

In Spring Boot this is true by default, and a warning appears at startup: "spring.jpa.open-in-view is enabled by default...". Most people ignore it.

What kind of problem comes up:

@GetMapping("/orders/{id}")
public OrderView get(@PathVariable long id) {
    Order o = orderService.find(id);           // the transaction ended
    var rate = currencyClient.rate("USD");     // external HTTP, 2 seconds
    return OrderView.of(o, o.getItems(), rate); // lazy loading, in the controller
}

With OSIV, o.getItems() works, but the connection is held even after the service transaction (in case it's needed for lazy loading). If the external call gets slow, a pool of 10 runs out at 10 parallel requests and the rest get Connection is not available. And in the database there's no query running; every connection is idle.

If you turn it off:

spring:
  jpa:
    open-in-view: false

Now lazy loading in the controller throws LazyInitializationException. That's a good thing: it openly shows which data wasn't loaded in the service layer. The fix: load the needed associations inside the service with JOIN FETCH or @EntityGraph, or return a DTO projection.

In an existing project, I run the full tests before turning it off, because a few endpoints will surely break.