To your point about why use HibernateCallback
. Short answer - it allows you to access the current transactionally bound session in order to do perform more complex hibernate functions. Most of the time the simple methods on HibernateTemplate
are sufficient, but sometimes you need to go down to the Session
.
There's two parts to the puzzle.
The first is the transaction scope which is defined either by using PlatformTransactionManager
/ TransactionTemplate
OR @Transactional
annotations. See the spring docs/google for more info.
The second is that when you are within a transaction HibernateTemplate
will interact with the current transaction using a bit of magic.
So a simple operation like hibernateTemplate.save()
will participate in the transaction. A more complex like your example will also participate in the transaction. In fact pretty much any method on hTemplate will participate.
So know to your question about when does the session get closed
- If you are using transactions explicitly, see first point above, then when the transaction scope closes the transaction will be committed and the session will be closed.
- Without transactions spring creates a session for you each time you call a
HibernateTemplate
method and closes it immediately afterwards. This is not the preferred approach as unless you are doing something very simple the results will be detached from the session and you will get LazyInit exceptions.
An important point to note in the second case above there is NO explicit transaction. You are at the mercy of the auto-commit mode of the connection so you might do, in a callback, save, save, throw exception. The first save MAY have been committed, without a transaction there's no guarantee.
My advice, when doing any updates, use a transaction.
If all the transaction stuff is new to you check the spring docs for the transaction chapter.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…