为什么休眠只在事务内自动刷新? [英] Why does Hibernate only Auto-Flush inside a transaction?
问题描述
此行为背后的原因是什么?
What is the rationale behind this behavior?
如果出于某种原因我在事务外执行了两个合适的操作(我不建议这样做,我不推荐!),并且已将Hibernate配置为自动刷新,那么我会期望将其自动刷新.第二个操作是应该触发自动刷新的操作(例如list
,iterate
或executeUpdate
).
If for some reason I execute two suitable operations outside a transaction (not recommended, I know!) and I've configured Hibernate to auto-flush, I would expect it to auto-flush if the second operation is one that should trigger an auto-flush (like list
, iterate
, or executeUpdate
).
如果不对autoFlushIfRequried
方法第二行进行显式检查,这就是将要发生的情况:
That's exactly what would happen, if not for the explicit check on the second line of the autoFlushIfRequried
method:
protected boolean autoFlushIfRequired(Set querySpaces) throws HibernateException {
errorIfClosed();
if ( ! isTransactionInProgress() ) {
// do not auto-flush while outside a transaction
return false;
}
AutoFlushEvent event = new AutoFlushEvent(querySpaces, this);
AutoFlushEventListener[] autoFlushEventListener = listeners.getAutoFlushEventListeners();
for ( int i = 0; i < autoFlushEventListener.length; i++ ) {
autoFlushEventListener[i].onAutoFlush(event);
}
return event.isFlushRequired();
}
更新:谢谢 axtavt ,发现了导致此更改的Hibernate问题(在3.2): FlushMode.AUTO->在事务外进行提交.
Update: Thank you axtavt for finding the Hibernate issue that prompted this change (in 3.2): FlushMode.AUTO -> COMMIT when outside a transaction.
一个相关的问题仍然存在:在FlushMode的情况下,延迟IDENTITY插入.MANUAL/NEVER ,但没有任何讨论提供说在交易之外进行操作时,FlushMode.AUTO是一件坏事."
A related issue is still open: delay IDENTITY insertions in the case of FlushMode.MANUAL/NEVER, but neither discussion provides the rationale for saying "When operating outside a transaction, FlushMode.AUTO is a bad thing."
推荐答案
因为FlushMode
的文档记录
有时,在执行查询之前会刷新会话,以确保查询永远不会返回陈旧状态.这是默认的刷新模式.
The Session is sometimes flushed before query execution in order to ensure that queries never return stale state. This is the default flush mode.
因此,汽车并不意味着您认为的含义.该名称可以说是选择不当,但这并不意味着在每次会话操作后都会进行刷新.因此,它与JDBC的自动提交不同,后者会在JDBC语句之后进行提交.
So, auto doesn't mean what you think it means. The name is, arguably, badly chosen, but it doesn't mean a flush is made after each session operation. It's thus not similar to JDBC's autocommit, which makes a commit after ever JDBC statement.
这篇关于为什么休眠只在事务内自动刷新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!