Will the session found in step 1 and step 3 will be the same session?
They should be the same, that's somehow part of the contract of getCurrentSession()
and you'll get the Session
bound to the thread as long as the unit of work has not been completed (i.e. a transaction has been committed or rolled back). Java Persistence with Hibernate puts it like this (p.481):
All the data-access code that calls getCurrentSession()
on the global shared
SessionFactory
gets access to the same current Session
— if it’s called in the
same thread. The unit of work completes when the Transaction
is committed (or rolled back). Hibernate also flushes and closes the current Session
and its persistence context if you commit or roll back the transaction. The implication here is that a call to getCurrentSession()
after commit or rollback produces a new Session
and a fresh persistence context.
And you might also want to read what the javadoc of Session#beginTransaction()
says.
If the answer for the question 1 is yes, then how would it handle the commit in step 4. Ideally it should close the session there itself and should give error at step 5.
Step 4 shouldn't be a problem, the Session
will be flushed, the Transaction
will be committed and the Session
closed. But I expect step 5 to fail wih aTransactionException
(that's my bet). But let me quote the javadoc of Transaction
:
A transaction is associated with a Session and is usually instantiated by a call to Session.beginTransaction()
. A single session might span multiple transactions since the notion of a session (a conversation between the application and the datastore) is of coarser granularity than the notion of a transaction. However, it is intended that there be at most one uncommitted Transaction associated with a particular Session at any time.
As underlined above, we are discussing around something that shouldn't happen (i.e. a design problem).