Java 当我们提供事务管理 api 时,为什么在 Hibernate 中自动提交默认为 false?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24683391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why autocommit is by default false in Hibernate when we have the Transaction management apis provided?
提问by sarathsoman
I'm not getting a clear idea of why autocommit is by default false in Hibernate when we have the Transaction management apis provided. I have three questions
当我们提供事务管理 api 时,我不清楚为什么自动提交在 Hibernate 中默认为 false。我有三个问题
why autocommit mode is not recommended by Hibernate?
What happens when we use autocommit = true and then use the Hibernate Transaction apis for transaction management ?
When using spring declarative transaction management how @Transactional(readonly = true) will help the read only code (Hibernate code) we write?
为什么 Hibernate 不推荐自动提交模式?
当我们使用 autocommit = true 然后使用 Hibernate Transaction apis 进行事务管理时会发生什么?
当使用 spring 声明式事务管理时,@Transactional(readonly = true) 将如何帮助我们编写的只读代码(休眠代码)?
采纳答案by Amogh
I will answer one by one Starting with (2) as i don't know much about (1)
我会一一回答从(2)开始,因为我对(1)了解不多
(2): autocommit=true means by default all queries get commited. In such case If
(2): autocommit=true 意味着默认所有查询都被提交。在这种情况下如果
if there is a @Transactional on a method, it overrides the autocommit and encloses all queries into a single transaction, thus overriding the autocommit
if there is a @Transactional method that calls other @Transactional annotated methods, the outer most annotation should override the inner annotaions and create a larger transaction, thus annotations also override eachother.
如果方法上有@Transactional,它会覆盖自动提交并将所有查询包含在一个事务中,从而覆盖自动提交
如果有一个@Transactional 方法调用其他@Transactional 注解的方法,最外层的注解应该覆盖内部的注解并创建一个更大的事务,因此注解也会相互覆盖。
(3): In DBs like Oracal/Mysql a read only transaction can be translated READ_ONLY level which provides no dirty reads, no unrepeatable reads but doesn't allow any updates. That means the flush mode will be set as FlushMode.NEVER
in the current Hibernate Session preventing the session from commiting the transaction. Even setReadOnly(true)
will be called on the JDBC Connection which ensure that you cannot call session.flsuh() even to flush session manually.
(3):在像 Oracal/Mysql 这样的数据库中,只读事务可以转换为 READ_ONLY 级别,它提供无脏读、不可重复读但不允许任何更新。这意味着刷新模式将设置为FlushMode.NEVER
当前休眠会话,以防止会话提交事务。EvensetReadOnly(true)
将在 JDBC 连接上调用,这确保您无法调用 session.flsuh() 甚至手动刷新会话。
since Spring doesn't do persistence itself, it cannot specify what readOnly should exactly mean. This attribute is only a hint to the provider, the behavior depends on, in this case, Hibernate.
由于 Spring 本身不进行持久化,因此它无法指定 readOnly 的确切含义。这个属性只是对提供者的一个提示,行为取决于,在这种情况下,Hibernate。