0

I need cast PoolableConnection to OracleConnection in runtime but I don't know how to do it. becasuse i got classCastException and if all classes extends Connection, can I do it ?

2 Answers2

3

You should just be able to cast to the DBCP specific Connection class and from there retrieve the inner Oracle connection:

import org.apache.commons.dbcp.DelegatingConnection;

DelegatingConnection dc = (DelegatingConnection)conn;
OracleConnection oc = (OracleConnection)pc.getInnermostDelegate();

If you are using Tomcat's built-in copy of DBCP then the import you will need is:

import org.apache.tomcat.dbcp.dbcp.DelegatingConnection;

Or you can use the connection pooling built into the Oracle JDBC driver implementation. This returns an Oracle connection. A simple setup would be:

<Resource auth="Container"
          connectionCacheName="CXCACHE"
          connectionCacheProperties="{MaxStatementsLimit=5,MinLimit=1, MaxLimit=1, ValidateConnection=true}"
          connectionCachingEnabled="true"
          description="Oracle Datasource"
          factory="oracle.jdbc.pool.OracleDataSourceFactory"
          name="jdbc/TestDB"
          user="default_user" 
          password="password"
          type="oracle.jdbc.pool.OracleDataSource"
          url="jdbc:oracle:thin:@//localhost:1521/orcl"
          />
Igor Nunes
  • 58
  • 1
  • 5
1

You can cast only if the object you're casting actually is an instance of the class you're casting it to. If you're getting a ClassCastException that's not the case.

All classes that extend Connection can be cast to a Connection, but not necessarily to each other.

Don Roby
  • 40,677
  • 6
  • 91
  • 113