Evgeni Dimitrov Evgeni Dimitrov - 1 year ago 199
Java Question

Spring JdbcTemplate alter session

I want to alter Oracle session for every connection that I get from the connection pool.

I found that it can be done by simply execute a statement. See here.

Is there a way to hook into the jdbc template or the datasource and execute a statement after the connection pool creates a new connection.

I'm using Spring Boot and creating the datasource that way:

public DataSource localDataSource() {
return DataSourceBuilder.create().build();

Answer Source

There are a lot of ways to do so. The first one:

  • DataSource is an inteface, so why don't you implement it yourself (use Proxy pattern)? Create something like this:

    class MyDataSource implements DataSource {
        private DataSource realDataSource;
        public Connection getConnection() {
              Connection c = realDataSource.getConnection();
              // do whatever you want to do and
              return c;

All other methods will delegate directly to realDataSource.

This proxy can be used in a provided code snippet.

  • You can use some AOP - just provide an advice that after get connection is created will run and do whatever you need there. Basically its the same proxy but automatically created by spring.

Hope this helps

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download