Reputation: 506
What's the difference between ManagedSessionContext
and ThreadLocalSessionContext
both has a ThreadLocal in their implementation for maintaining sessions
Upvotes: 0
Views: 1154
Reputation: 8247
ThreadLocalSessionContext
- It takes care of the hibernate session management activities like :
sessionFactory.getCurrentSession()
returns this bound session and unbinds it once the transaction is completed.ManagedSessionContext
- Responsibility of session management activities like above are handled by some external entity (generally some form of interceptor, etc).
In both the cases the session is stored in the ThreadLocal though.
But the call to bind/unbind of the session and especially when to call flush and close on the session are defined via the external entity.
This gives more flexibility, for example, in the case of ThreadLocalSessionContext
, the session is closed automatically when the transaction ends and it is not possible to leave the session open for multi-request conversation type of requirements.
In case of ManagedSessionContext
, we can implement multi-request conversation (a.k.a session-per-conversation model
) the same session needs to be kept open and should be reused across the user requests. So in the first user request we insert/update/delete some entities and in the next request we do some more operations and finally at the end of third interaction we want to commit the data.
Quoting from Managing the current Session section
When a conversation starts, a new Session must be opened and bound with ManagedSessionContext.bind() to serve the first request in the conversation. You also have to set FlushMode.MANUAL on that new Session, because you don’t want any persistence context synchronization to occur behind your back.
All data-access code that now calls sessionFactory.getCurrentSession() receives the Session you bound.
When a request in the conversation completes, you need to call Managed-SessionContext.unbind() and store the now disconnected Session somewhere until the next request in the conversation is made. Or, if this was the last request in the conversation, you need to flush and close the Session.
To represent that pictorially,
Session-per-conversation
using ManagedSessionContextYou can go through the Listing 11.5 of this link for a sample implementation an interceptor that manages the session for session-per-conversation
model.
Upvotes: 4