简体   繁体   English

连接关闭时活动事务的行为?

[英]Behaviour of active transaction on connection close?

If the close method is called and there is an active transaction, what will happen to active transactions?如果调用了 close 方法并且有一个活动事务,那么活动事务会发生什么? Will they be commited or rolled back?他们会被提交还是回滚?

Adding to the other answer, I tested the behavior on Oracle and SQL Server, the databases I'm currently working with.添加到另一个答案中,我测试了 Oracle 和 SQL 服务器上的行为,这是我目前正在使用的数据库。

MSSQL rolls back the transaction. MSSQL回滚事务。 This is what you'd intuitively expect.这是您直观地期望的。

Oracle on the other side, commits the transaction.另一边的 Oracle提交事务。 This is documented in their JDBC Guide :这记录在他们的JDBC 指南中:

If the auto-commit mode is disabled and you close the connection without explicitly committing or rolling back your last changes, then an implicit COMMIT operation is run.如果自动提交模式被禁用并且您关闭连接而没有显式提交或回滚您的最后更改,则运行隐式 COMMIT 操作。

Sure, the JDBC spec gives you freedom to go either way, but I personally think that implicitly committing the transaction is a poor design choice.当然,JDBC 规范让您可以自由选择 go,但我个人认为隐式提交事务是一个糟糕的设计选择。 As an argument, consider the use case of a thread which is busy working on a long-ish transaction and is not responsive to a shutdown request.作为一个论点,考虑一个线程的用例,它忙于处理一个长事务并且没有响应关闭请求。 When the application eventually closes the connection pool, this will in turn close the connection, committing the incomplete transaction!当应用程序最终关闭连接池时,这将反过来关闭连接,提交不完整的事务!

The moral of this story is that connection pool implementations must always call rollback() before closing a connection in manual commit mode.这个故事的寓意是,连接池实现必须始终在手动提交模式下关闭连接之前调用 rollback()。 However this is not something that just comes to mind when implementing a connection pool.然而,这并不是在实现连接池时才想到的。 As an example, see PooledConnectionImpl from DBCP例如,请参阅DBCP 中的 PooledConnectionImpl

From the javadoc of Connection.close() :Connection.close()的javadoc:

It is strongly recommended that an application explicitly commits or rolls back an active transaction prior to calling the close method.强烈建议应用程序在调用 close 方法之前显式提交或回滚活动事务。 If the close method is called and there is an active transaction, the results are implementation-defined.如果调用 close 方法并且存在活动事务,则结果是实现定义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM