Evgeni Dimitrov Evgeni Dimitrov - 23 days ago 5
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:

@Bean
@ConfigurationProperties(prefix="datasource.local")
public DataSource localDataSource() {
return DataSourceBuilder.create().build();
}

Answer

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

Comments