This article will teach how you can fetch the underlying Connection from either the java.sql.Connection
object or the EntityManager
( for Hibernate and JPA Applications).
Accessing the Underlying Connection
If you need to access to the specific driver connection (for example the OracleConnection instead of the java.sql.Connection) then you need to use the WrappedConnection object and get its underlying connection:
Connection c = dataSource.getConnection(); org.jboss.resource.adapter.jdbc.WrappedConnection wc = (WrappedConnection) c; OracleConnection ajc = (OracleConnection ) wc.getUnderlyingConnection();
Please note this class is available in the ironjacamar-jdbc-1.x.xx.Final.jar module which is included in WildFly / JBoss EAP distribution.
Another option is to call via reflection the getUnderlyingConnection method. Here’s an example for Oracle:
public static OracleConnection getOracleConnection(Connection conFromPool) throws SQLException { try { Class[] parms = null; Method method = (conFromPool.getClass()).getMethod("getUnderlyingConnection", parms); return (OracleConnection) method.invoke(conFromPool, parms); } catch (InvocationTargetException ite) { throw new SQLException(ite.getMessage()); } catch (Exception e) { throw new SQLException(e.getMessage()); } }
Accessing the Connection from the Entity Manager
In order to get the Connection from an EntityManager
, you need to unwrap the EntityManager
as follows:
@PersistenceContext private EntityManager em; //.... em.unwrap(SharedSessionContractImplementor.class).getJdbcCoordinator().getLogicalConnection().getPhysicalConnection();
In a similar way, you can obtain the ExceptionConverter
, that converts a Hibernate-specific exception into a JPA-specified exception;
private ExceptionConverter getExceptionConverter(EntityManager em) { return em.unwrap(SharedSessionContractImplementor.class).getExceptionConverter(); }