Search code examples
javaspring-bootoracle11g

Obtain an OracleDataSource in SpringBoot 2


Is it possible to retrieve a OracleDataSource from the default SpringBoot 2 Hikari connection pool using a NamedParameterJdbcTemplate object? Using Java 8, Oracle 11g (ojdbc6-11.2.0.1.jar) and gradle This is what i've tried.

@Repository
public class MyClass{

@Autowired
NamedParameterJdbcTemplate  jdbcTemplate;

public void myMethod(){
try{
    //OracleDataSource ods = new OracleDataSource();                                            // This works but is obviously not Spring
    OracleDataSource ods = (OracleDataSource) jdbcTemplate.getJdbcTemplate().getDataSource();   // This fails

    ods.setURL(url);
    ods.setUser(user);
    ods.setPassword(pass);

    ...
    catch(Exception e){
            System.out.println("In Exception");
            e.printStackTrace();
    }
}

}

Application.properties:

spring.datasource.url=jdbc:oracle:thin:@//${ORA_HOST}:${ORA_PORT}/${ORA_SID}
spring.datasource.username=${USER}
spring.datasource.password=${PASS}  

Error message:

In Exception
java.lang.ClassCastException: com.zaxxer.hikari.HikariDataSource cannot be cast to oracle.jdbc.pool.OracleDataSource

Solution

  • I don't think this is possible (or neccessary). The easiest way is to unwrap() a connection object, which has already connected to the dB:

    Connection conn =  this.jdbcTemplate.getJdbcTemplate().getDataSource().getConnection().unwrap(OracleConnection.class);