Video in progress

In Spring Boot open-in-view is on by default. How do you justify turning it off across the whole organization?

OSIV stretches lazy loading out to the view and serialization: connections stay busy longer, N+1 gets hidden, and SQL runs outside a transaction. Turning it off is painful, but it surfaces the problems instead of hiding them, so I make the default false in new services.

📖 Answer

Spring Boot does not print the "spring.jpa.open-in-view is enabled by default" warning at startup for nothing.

With OSIV on, the EntityManager is opened at the start of the request and not closed until the response is written. If you return an entity from a controller, Jackson calls order.getItems() and Hibernate sends SQL at that moment: outside a transaction, in autocommit mode. On screen everything works, so nobody notices.

The consequences show up under load:

  • the connection stays busy during serialization and while writing the response to a slow client, so the pool runs out fast;
  • the N+1 is hidden in the controller layer, and service tests don't see it;
  • every lazy load is its own mini-transaction, so there is no consistent snapshot.

This is how I push the decision through. For new services, the template has open-in-view: false. For existing services I measure first: with datasource-proxy we log the number of queries going out outside a transaction. Then we turn it off service by service, find the LazyInitializationExceptions with integration tests, and fix them with DTO projections or fetch joins.

I back up the rule "don't return entities from a controller" with ArchUnit, because after OSIV is off, that is where most of the errors appear.

As an exception, OSIV can stay on small admin panels that use server-side rendering (Thymeleaf): the load there is low and convenience matters more. But that has to be a deliberate, written-down decision.