从的观点,与关闭会话和 flush
应该发生在事务的边界内(或者在
commit
时间):
另一方面,关闭一个Session(和底层连接)应该在一个事务结束后完成关闭连接时挂起事务的行为是未定义)。
因此,没有理由关闭任何事情并促成不良的语义,并且具有不同的操作是非常合理的。
总结:
- just 使用事务并且正确(如果需要,会话将在提交时刷新,具体取决于FlushMode)。
- 使用
SessionFactory#getCurrentSession()
,您不必为Session#close() code>你自己(在提交时
Session
会在你提交时关闭)。
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?
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):
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).
这篇关于为什么hibernate session.close()不会自动刷新数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!