Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect open transaction not yet committed in JDBC connection

How do I detect if a transaction remains open, still pending on a COMMIT or ROLLBACK on a JDBC Connection?

I'm getting my Connection objects via a connection pool. So I want to check the state of the connection before using it.

Using Postgres 9.x and Java 8.

like image 890
Basil Bourque Avatar asked Jul 31 '15 19:07

Basil Bourque


2 Answers

I'm not aware of any way to detect current transaction status on a Connection using only standard JDBC API methods.

However, for PostgreSQL specifically, there is AbstractJdbc2Connection.getTransactionState(), which you can compare against the constant ProtocolConnection.TRANSACTION_IDLE. PostgreSQL's JDBC4 Connection extends this class so you should be able to cast your Connection to get access to this property.

That constant is one of three values defined in the pgjdbc driver source code:

/**
 * Constant returned by {@link #getTransactionState} indicating that no
 * transaction is currently open.
 */
static final int TRANSACTION_IDLE = 0;

/**
 * Constant returned by {@link #getTransactionState} indicating that a
 * transaction is currently open.
 */
static final int TRANSACTION_OPEN = 1;

/**
 * Constant returned by {@link #getTransactionState} indicating that a
 * transaction is currently open, but it has seen errors and will
 * refuse subsequent queries until a ROLLBACK.
 */
static final int TRANSACTION_FAILED = 2;
like image 171
heenenee Avatar answered Sep 23 '22 16:09

heenenee


As I understand, you use plain JDBC and this is why you have this problem. Because you told about the Tomcat's JDBC Connection Pool, you could use JDBCInterceptor.invoke(), where you could track what happens to each Connection. More details here.

like image 42
V G Avatar answered Sep 22 '22 16:09

V G