Video in progress
What is spring.jpa.open-in-view, and why do many people recommend turning it off?
Open Session in View keeps the Hibernate session open for the whole HTTP request, until the JSON is written. In Boot it is on by default and warns at startup. It hides lazy errors, but in exchange it holds a DB connection for a long time and creates invisible queries.
📖 Answer
The application prints this at startup:
spring.jpa.open-in-view is enabled by default. Therefore, database queries may be
performed during view rendering.
What happens when it is on:
- An
EntityManageris opened at the start of the request. - The service transaction ends, but the session is not closed.
- While Jackson serializes the entity, it touches lazy fields, and each one fires a new SQL query.
- Those queries run without a transaction (auto-commit), and the connection stays busy until the response is fully written.
Why it's bad: even while a big response is being written to a slow client, the connection stays checked out of the pool, and under load the pool runs dry. N+1 hides in the serialization layer, so you can't see it by reading the code.
In a new project, turn it off from the start:
spring:
jpa:
open-in-view: false
and return DTOs from the service. If you turn it off in an old project, LazyInitializationExceptions will start to appear. In reality that's a list of hidden problems, and you fix them one by one.
Sign up to mark studied questions and save your progress.