Extract JDBC Connection from Entitymanager using JTA

Asked

Viewed 1,186 times

2

In an environment Javaee, there is the possibility to extract the JDBC connection(java.sql.Connection) using JTA?

I have a datasource in Wildfly, where I inject in the following way:

@PersistenceContext
private EntityManager entityManager;

Have any way to extract the JDBC connection from this Entitymanager?

I found a way (but it didn’t work):

Connection connection = entityManager.unwrap(java.sql.Connection.class);

The following error has been released:

javax.persistence.Persistenceexception: Hibernate cannot unwrap java.sql.Connection interface

2 answers

1

Hibernate and JPA 2.0

 @PersistenceContext
 private EntityManager entityManager;   

 session session = entityManager.unwrap(Session.class);

 SessionFactoryImplementor sfi = (SessionFactoryImplementor) 
 session.getSessionFactory();

 ConnectionProvider cp = sfi.getConnectionProvider();

 Connection conn = cp.getConnection();

Eclipselink JPA 2.0

 @PersistenceContext
 private EntityManager entityManager; 

 java.sql.Connection connection  entityManager.unwrap(java.sql.Connection.class);

http://wiki.eclipse.org/EclipseLink/Examples/JPA/EMAPI#Getting_a_JDBC_Connection_from_an_EntityManager

  • SessionFactoryImplementor does not have the method getConnectionProvider

  • What is the version of your JPA implementation ?

  • Java ee 7, i.e., JPA 2.0

1

The way I did it was this:

Session hibernateSession = this.entityManager.unwrap(Session.class);
return ((SessionImpl) hibernateSession).connection();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.