Why hibernate session.close() does not flushes the data automatically?
When hibernate closes a session, the purpose of close is basically to close the underlying connection and the clean up the fi开发者_JAVA技巧rst level cache. Why the flush also does not happens automatically here?
From a transactional point of view, flushing is very different from closing the session and flush
should occur inside the boundaries of a transaction (or at commit
time):
Ending a Session usually involves four distinct phases:
- flush the session
- commit the transaction
- close the session
- handle exceptions
On the other hand, closing a Session (and the underlying connection) should be done after a transaction has ended (the behavior of a pending transaction when closing a connection is undefined).
There is thus no reason to do anything on close and to promote bad semantics and it makes perfect sense to have distinct operations.
To sum up:
- just use a transaction and proper demarcation as you're supposed to (and the session will get flushed at commit time if required, depending on the FlushMode).
- use
SessionFactory#getCurrentSession()
and you won't have toSession#close()
yourself (theSession
will get closed for you at commit time).
精彩评论