Extract JDBC Connection from EntityManager using JTA

1

In a JavaEE environment, is it possible to extract the JDBC connection ( java.sql.Connection ) using JTA ?

I have a datasource in WildFly, where I inject as follows:

@PersistenceContext
private EntityManager entityManager;

Is there any way to extract the JDBC connection from this EntityManager?

I found a form (but it did not work):

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

The following error was thrown:

  

javax.persistence.PersistenceException: Hibernate can not unwrap   interface java.sql.Connection

    
asked by anonymous 08.01.2018 / 19:47

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);

link

    
08.01.2018 / 21:39
0

The way I did it, was as follows:

Session hibernateSession = this.entityManager.unwrap(Session.class);
return ((SessionImpl) hibernateSession).connection();
    
22.01.2018 / 17:58