springhibernatespring-data-jpatransactionsopen-session-in-view

Open Session In View OSIV - Does this happen for every request / thread?


I have turned off the OSIV in a Spring project as I have been reading why it (controversially) may be a bit of an anti-pattern. Not wanting to poke that debate as I have seen it gets heated but I am more interested/lost in the technicals.

Either way, I was wondering exactly when does a session become opened? Is it for ANY web request that comes in or is there some way the application knows that it will only be needing a session for certain endpoints? I am guessing the OSIV Filter is basically always called for every request and a hibernate session to the DB is aquired and added to the webrequest/thread?

I.e. is it OSIV for everything or only certain requests get the session bound through the entire filter chain and then the controller/services and back out?

When they say "session" I am right in assuming that means it has gotten an active jdbc connection and opened connection to the database...even if I may not use it, and that is where the sort of blocking IO problems could occur say if we are waiting on 3rd party responses although we are now out of a @Transactional service method boundary and we get a spike in traffic?

What exactly is opened session wise? Is a database transaction started via the session "just in case" on every request? Or is there just a hibernate session created for each request and then a transaction is only started if a JPA/Hibernate query is started somewhere along the request (with or without @Transactional).

Any clarification would be excellent!

Vlad Mihalcea - OSIV Anti-Pattern

Baeldung - OSIV


Solution

  • Transactions are only started when you run a method annotated with @Transactional. OSIV just eagerly opens/creates a Hibernate session which can be used for lazy loading through out the whole request lifecycle, but the connection is only acquired lazily i.e. on first database access. Once it is acquired, it depends on certain settings when the connection will be released, but usually it is kept open until the session closes.