Monday, August 29, 2005

Getting the underlying JDBC Connection from JBoss wrapped Connect ion.

While using connection pools with xa-datasource and xa-connections, sometimes it becomes necessary to extract the underlying JDBC connection object from the wrapped connection object returned by a JBoss datasource look-up. This is especially the case when you want to invoke some of the non-standard methods which are provided by the DataSource and Connection implementations that you are using. We will use reflection to invoke the getUnderlyingConnection() method on the wrapped connection returned by ds.getConnection( ) at runtime.
 
private static Connection con;
private Connection jbosscon;
private Class wrappedConnectionClass;
private Method getUnderlyingConnectionMethod;
 
 
try {
            this.wrappedConnectionClass = getClass().getClassLoader().loadClass("org.jboss.resource.adapter.jdbc.WrappedConnection");
            this.getUnderlyingConnectionMethod = this.wrappedConnectionClass.getMethod("getUnderlyingConnection", (Class[]) null);
            Context jndiCntx = new InitialContext();
            
            DataSource ds = (javax.sql.DataSource)jndiCntx.lookup("java:/jdbc/sibr" );
            jbosscon = ds.getConnection(db_user,getUserPasswd(db_user));
            con = (Connection) this.getUnderlyingConnectionMethod.invoke(jbosscon, (Object[]) null);
            con.setAutoCommit(false);
}
catch (Exception e) {
           e.printStackTrace();
}

No comments: