Why hibernate session.close() does not flushes the data automatically?

非 Y 不嫁゛ 提交于 2019-12-07 22:19:40

问题


When hibernate closes a session, the purpose of close is basically to close the underlying connection and the clean up the first level cache. Why the flush also does not happens automatically here?


回答1:


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).


来源:https://stackoverflow.com/questions/1969109/why-hibernate-session-close-does-not-flushes-the-data-automatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!