05 Январь, 2010

tomcat datasource native connection

Sometimes need use native db connection.
For example, to correct the following exception:

java.lang.ClassCastException: org.apache.tomcat.dbcp.dbcp.PoolingDataSource cannot be cast to oracle.jdbc.OracleConnection



private String datasource = "java:comp/env/jdbc/mydb";

private DataSource getDataSource() {
InitialContext ctx;
try {
ctx = new InitialContext();
BasicDataSource ds = (BasicDataSource) ctx.lookup(datasource);
ds.setAccessToUnderlyingConnectionAllowed(true);
return ds;
} catch (NamingException e) {
throw new RuntimeException(e);
}
}

private Connection getNativeConnection(Connection connection) {
return ((DelegatingConnection) connection).getInnermostDelegate();
}

public void doIt() {
Connection connection = null;
try {
connection = getDataSource().getConnection();
Connection nativeConnection = getNativeConnection(connection);
doSomethingWithNativeConnection(nativeConnection);
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

}

private void doSomethingWithNativeConnection(Connection connection) {
System.out.println(connection.getClass());
/*- for oracle will be print:
class oracle.jdbc.driver.T4CConnection
*/
// ...
}


For example context.xml below:

<Resource name="jdbc/mydb" auth="Container" type="javax.sql.DataSource"
maxActive="10" maxIdle="10" maxWait="10000" username="user" password="password"
driverClassName="oracle.jdbc.OracleDriver" url="jdbc:oracle:thin:@localhost:1521:orasid"
validationQuery="select 1 from dual" />