oracle.jdbc.pool.OracleDataSource为每个新连接运行一个命令

时间:2013-03-18 21:28:48

标签: java oracle jdbc connection-pooling pool

我想对来自特定oracle.jdbc.pool.OracleDataSource连接池的每个新连接执行ALTER SESSION命令。有没有办法做到这一点?

2 个答案:

答案 0 :(得分:1)

如果要部署到应用程序服务器,请检查配置选项,在许多情况下,您可以在那里配置一些“初始SQL”。

如果您不能这样做,请在应用程序级别使用自定义DataSource包装oracle.jdbc.pool.OracleDataSource,然后在应用程序的其余部分中使用该自定义DataSource。类似的东西:

public class InitialSqlDataSource implements DataSource {
    private DataSource delegate;
    private String initialSql;


    public InitialSqlDataSource(DataSource delegate, String initialSql) {
        this.delegate = delegate;
        this.initialSql = initialSql;
    }

    public void setDelegate(DataSource delegate) {
        this.delegate = delegate;
    }

    public void setInitialSql(String initialSql) {
        this.initialSql = initialSql;
    }

    @Override
    public Connection getConnection() {
        Connection connection = delegate.getConnection();
        if (connection != null && isNew(connection)) {
            issueInitialSql(connection);
        }
        return connection;
    }

    protected boolean isNew(Connection connection) {
        // Logic to find out if connection is a new one
        // or a previously pooled connection. In the worst
        // case you can approximate this logic by always returning 
        // true. This will issue the initial SQL on every retrieval 
        // of a connection from this DataSource. This will
        // add some overhead, but will work in many cases.
        return true;
    }

    protected void issueInitialSql(Connection connection) {
        // A typical JDBC statement execution, adapted to
        // your particular needs
        ...
    }

    // Delegate every other method to this.delegate
    ...
}

答案 1 :(得分:0)

您可以在每个新连接上执行自定义代码(或者,在最坏的情况下,在连接池中的每个“get”上执行自定义代码)。另一方面,如果可行,您可以在特定模式上创建LOGON TRIGGER。