Jooq使用现有连接进行fetchOne或执行

时间:2014-12-27 01:12:28

标签: java jdbc playframework-2.0 jooq

我尝试在play框架中自己管理连接,并实现jooq Connection提供程序:

public class PlayConnectionProvider implements ConnectionProvider {

  private Connection connection = null;

  @Override
  public Connection acquire() throws DataAccessException {
    if (connection == null) {
      connection = DB.getConnection();
    }
    return connection;
  }

  @Override
  public void release(Connection released) throws DataAccessException {
    if (this.connection != released) {
      throw new IllegalArgumentException("Expected " + this.connection + " but got " + released);
    }
    try {
      if (connection.getAutoCommit() == true) {
        connection.close();
        connection = null;
      }
    } catch (SQLException e) {
      Logger.error("Error closing connection " + connection, e);
    }
  }
}

然而,当我调用execute()时,似乎jooq将始终调用acquire()并创建一个新连接而不是使用现有连接。我发现新的连接是由execute()函数中的DefaultExecuteContext获得的:

public final Connection connection() {
    ConnectionProvider provider = this.connectionProvider != null?this.connectionProvider:this.configuration.connectionProvider();
    if(this.connection == null && provider != null) {
        this.connection(provider, provider.acquire());
    }

    return this.connection;
}

有没有办法为execute()配置连接?

1 个答案:

答案 0 :(得分:0)

你是对的,jOOQ总是在每次execute()来电时调用acquire()。但它最后也会调用release(),而您似乎正在重置自己的缓存连接

if (connection.getAutoCommit() == true) {
    connection.close();
    connection = null;
}

...因为Play的DB.getConnection()返回启用了自动提交的连接

关于线程安全的说明

请注意,如果您以这种方式缓存连接,ConnectionProvider将不再是线程安全的,因此包含它的所有对象也不是线程安全的(包括Configuration and DSLContext)。保持此线程安全的一种方法是将连接存储在ThreadLocal

内的ConnectionProvider