About OSIV (Open Session In View): True or False?
2 min read
Overview
OSIV (Open Session In View) is a feature that leaves the persistence context open to the view. When the persistence context is maintained, entities also remain persistent.
Persistence context is an environment where entities are stored permanently.
We can simply set it in the configuration file. It is enabled by default.

For an API, it stays alive until the response is sent to the client.
open-in-view: true

open-in-view: false

- When OSIV is turned off (false), the persistence context is closed when the transaction ends, and the database connection is also returned. Therefore, connection resources are not wasted.
- All lazy loading must be handled within the transaction.
Code
Let me give a brief example. Users can create multiple posts, and this relationship is 1:N.
Entity

Post

User
When the User is found, the Post in the User becomes a proxy object because it is lazy loading.

Generating initial values
Now let’s compare the false and true situations.
I’m going to make a simple endpoint in the Controller
and check the true case.

Controller
It is a function that receives a user ID as a parameter and finds the user information.

Response
return ResponseEntity.ok().body(UserDto.builder()
.id(result.getId())
.name(result.getName())
.password(result.getPassword())
.join_date(result.getJoin_date())
.posts(result.getPosts()).build());
This code requested a proxy object, and it was lazy loaded.
Now let’s check the false situation (spring.jpa.open-in-view: false).

Response
This is because lazy loading was attempted in the controller, outside the transaction range, where the persistence context was already closed.
- true Maintains the persistence context until the response is sent to the client or the view is rendered
- false The persistence context is also closed after the transaction
Maintaining the persistence context means the DB connection is also held. In applications where real-time traffic is critical, DB connections might run short. If performance is critical, set OSIV to false.
If the OSIV option is set to false, you should handle and transform entity objects within the Transaction annotation.