简体   繁体   中英

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

MSSQL rolls back the transaction. This is what you'd intuitively expect.

Oracle on the other side, commits the transaction. This is documented in their JDBC Guide :

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.

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. 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. However this is not something that just comes to mind when implementing a connection pool. As an example, see PooledConnectionImpl from DBCP

From the javadoc of Connection.close() :

It is strongly recommended that an application explicitly commits or rolls back an active transaction prior to calling the close method. If the close method is called and there is an active transaction, the results are implementation-defined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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