Luckas Negrini
Luckas Negrini

Reputation: 3

how to cast dbcp connection to oracle connection?

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 ?

Upvotes: 0

Views: 1834

Answers (2)

Igor Nunes
Igor Nunes

Reputation: 58

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"
          />

Upvotes: 3

Don Roby
Don Roby

Reputation: 41137

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.

Upvotes: 1

Related Questions