Search code examples
javaentitymanagerc3p0

Unwrap NewProxyConnection and GetConnection from NewProxyConnection


I have the following structure:

  1. A layer with Hibernate 4.0.1, using C3P0 as connection Pool.
  2. I don't have datasources configured, I use a dynamic configuration of datasource like it:

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("persitenceUnit", createMap(ds)); 
    

'ds' is a object with my database properties, like user, password, url, ...

  1. I get Entitymanager this way:

    EntityManager em = emf.createEntityManager();
    
  2. I try get connection this way:

    EntityManagerImpl entityManagerImpl = (EntityManagerImpl)em;
    SessionFactoryImpl sessionFactoryImpl = (SessionFactoryImpl)entityManagerImpl.getSession().getSessionFactory();
    Connection con = sessionFactoryImpl.getConnectionProvider().getConnection();
    

But, con is a NewProxyConnection instance. I need execute a procedure that return an ORAData and con.prepareCall(sqlToProcedure) return a NewProxyCallableStatment that no have a getOraData, ie, this code don't work:

OracleCallableStatment ocs = (OracleCallableStatment)con.prepareCall('{call stp_test(?)}');   
ocs.excute();    
TestObjectodf to = ocs.getOraDATA(1, TestObject.getOraDataFactory());    

The error happens in

OracleCallableStatment ocs = (OracleCallableStatment)con.prepareCall('{call stp_test(?)}');

I try:

NewProxyConnection npCon = sessionFactoryImpl.getConnectionProvider().getConnection();
Connection con = npCon.unwrap(Connection.class);

But don't work.


Solution

  • The unwrap() method will work, if you upgrade to the latest c3p0-0.9.5 prerelease version. unwrap() is a JDBC4 method, supported by c3p0 as of c3p0-0.9.5. Since you want an OracleCallableStatement, you will probably want to call the unwrap() method of a CallableStatement, rather than the unwrap() method of a Connection, as you try above.

    Alternatively (and a bit more safely), with almost any version of the library, you can use c3p0's raw statement operations. See the docs.