开发者

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:

  1. 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).
  2. use SessionFactory#getCurrentSession() and you won't have to Session#close() yourself (the Session will get closed for you at commit time).
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜