Video in progress
What is spring.jpa.open-in-view, and why does Spring Boot warn you about it at startup?
Open-in-view (OSIV) keeps the persistence context open for the whole HTTP request, until the view or JSON is written. In Spring Boot it's true by default. That's why touching lazy fields in a controller works without errors, but at the cost of hidden SQL and a DB connection held for a long time.
📖 Answer
The startup warning goes roughly: "spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering."
What happens with OSIV on:
@GetMapping("/orders/{id}")
public Order get(@PathVariable Long id) {
return service.find(id); // the transaction is over
}
// Jackson calls order.getItems(), item.getProduct()...
// each one is a new SELECT with no transaction, in auto-commit mode
The problems:
- N+1 queries hide in serialization, where you can't see them in the service code;
- the connection can be busy from the start of the request to the end. A connection is taken from the pool even while the response is being written to a slow client. Under load the pool runs out fast;
- it gets harder to control which data is loaded where.
In new projects I turn it off right away:
spring.jpa.open-in-view: false
After that, the places where LazyInitializationException appears show you exactly which query needs a fetch join or a DTO. In a big legacy project, turning it off all at once breaks a lot, so you do it step by step there, with tests.
Sign up to mark studied questions and save your progress.