Java – How does transaction propagation work when using Open Session In View

hibernatejavaspringtransactions

I'm really confused about transaction propagation in Spring with Hibernate. I use Spring @Transactional annotations on my service layer methods. Some are marked as 'read-only=true'. If one of my read-only service methods calls a method that is not read-only, how can I deal with this?

I'm thinking I can mark all my read-write methods to support REQUIRES_NEW propagation but this would result in behaviour that I may not want – i.e. I only want a new transaction in the case that a read-only method is called a read-write method. If a read-write method calls another read-write method, I wouldn't need a new transaction.

Taking all this into consideration, I don't understand how Open Session In View (OSIV) works! Surely, using OSIV in Spring, the OpenSessionInViewFilter must have to start a transaction prior to service methods being called. In that case, it must have to define whether the transaction is read-only or read-write. BUT, how can it know this? It doesn't know what is going to happen under the covers of the service layer.

I'm completely in the dark on all of this and would love somebody to explain it to me!

Best Answer

The lifecycle of Hibernate sessions is different to that for transactions. The two can overlap each other.

In the case of OpenSessionInViewFilter, this has nothing to do with transactions at all, it just manages the lifecycle of the Hibernate session during the request. When a Spring-transactional method is called, a new transaction is started, and associated with the hibernate session, and then committed/rolled back when the method exits. The session is then closed by the filter when the request finishes. There's no need to start/finish the transaction at the same time as the session.

As for your read-only transaction question (which is a different issue altogether, incidentally), this is really nothing more than a hint to the underlying database that no data will be modified. I've never seen this have any concrete effect, though, it seems to be more useful as a documentation tool than anything else.