简体   繁体   中英

oracle.jdbc.pool.OracleDataSource run a command for every new connection

I would like to execute an ALTER SESSION command on every new connection coming from a particular oracle.jdbc.pool.OracleDataSource connection pool. Is there a way to do that?

If you are deploying to an application server, check the configuration options, in many cases you can configure some "initial SQL" there.

If you cannot do is that way, wrap oracle.jdbc.pool.OracleDataSource with a custom DataSource at the application level, then use that custom DataSource in the rest of your application. Something like:

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

You can do custom code on each new connection (or, in worst case, on each "get" from connection pool). On the other hand, if feasible, you can create LOGON TRIGGER on particular schema.

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