获取为JDBC 4.2更新的org.postgresql JDBC驱动程序中的事务状态

时间:2015-09-22 23:34:36

标签: postgresql jdbc driver

问题

Postgres的org.postgresql JDBC driverJDBC 4.2JEP 170)的新版本。带有用于动态确定Connection事务状态的类的旧包已经消失。现在用什么?

背景

奇怪但真实,JDBC无法识别事务的状态。因此,例如,从池中获取连接时,您无法验证是否存在因先前使用而挂起的待处理事务。

作为一种解决方法,您可以在JDBC驱动程序中调用Postgres特定的方法来确定状态是空闲(无txn),打开(挂起txn)还是失败(txn中的错误)。

在之前的版本中,9.4-1201-jdbc41(请注意41 vs 42,即JDBC 4.2),您可以编写这样的代码。

if ( conn instanceof org.postgresql.jdbc2.AbstractJdbc2Connection ) {
    // Cast from a generalized JDBC Connection to one specific to our expected Postgres JDBC driver.
    org.postgresql.jdbc2.AbstractJdbc2Connection aj2c = ( org.postgresql.jdbc2.AbstractJdbc2Connection ) conn; // Cast to our Postgres-specific Connection.

    // This `getTransactionState` method is specific to the Postgres JDBC driver, not general JDBC.
    int txnState = aj2c.getTransactionState();
    // We compare that state’s `int` value by comparing to constants defined in this source code:
    // https://github.com/pgjdbc/pgjdbc/blob/master/org/postgresql/core/ProtocolConnection.java#L27
    switch ( txnState ) {
        case org.postgresql.core.ProtocolConnection.TRANSACTION_IDLE:
            stateEnum = DatabaseHelper.TransactionState.IDLE;
            break;

        case org.postgresql.core.ProtocolConnection.TRANSACTION_OPEN:
            stateEnum = DatabaseHelper.TransactionState.OPEN;
            break;

        case org.postgresql.core.ProtocolConnection.TRANSACTION_FAILED:
            stateEnum = DatabaseHelper.TransactionState.FAILED;
            break;

        default:
            // No code needed.
            // Go with return value having defaulted to null.
            break;
    }
} else {
    logger.error( "The 'transactionStateOfConnection' method was passed Connection that was not an instance of org.postgresql.jdbc2.AbstractJdbc2Connection. Perhaps some unexpected JDBC driver is in use. Message # 47a076b1-ba44-49c7-b677-d30d76367d7c." );
    return null;
}

当前的驱动程序是JDBC42 Postgresql Driver, Version 9.4-1203。在这个新的驱动程序中,org.postgresql.jdbc2包似乎已经消失了。什么是替代品?

0 个答案:

没有答案