Search⌘ K
AI Features

Open Session in View

Explore the concept of Open Session In View in Spring Boot and why it is often considered an anti-pattern. Understand how OSIV works to keep database sessions open for lazy loading and the potential performance issues it can cause. Learn best practices to disable OSIV, avoid LazyInitializationException using lazy loading and join fetch strategies, and optimize database access in scalable applications.

What is OSIV?

If we observe the logging output of the Spring Boot application, we will see this warning:

Shell
2020-09-08 17:06:32.095 WARN 75541 --- [ main]
JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by
default. Therefore, database queries may be performed during view rendering.
Explicitly configure spring.jpa.open-in-view to disable this warning.

By default, Spring Boot has Open Session In View (OSIV) enabled. However, this is considered to be an antipattern by many.

Why is OSIV an anti-pattern?

To answer that question, let’s first explain what Open Session In View does. Put simply:

The Session is what JPA/Hibernate needs to make the database work.

When a controller calls a service, a transaction is started and spans all database calls that the service does (via a repository). The transaction/session is closed when the service ...