Eduardo
Eduardo

Reputation: 1199

Get JDBC connection from EntityManager

I've a web application that uses EJB 3. Persistence is managed by container so the entity manager is injected.

@PersistenceContext(name="Ejbs", type=PersistenceContextType.TRANSACTION)
private EntityManager em;

I need in one of my EJB methods to get the jdbc connection. I've read that it is possible with the next code:

java.sql.Connection conn = em.unwrap(java.sql.Connection.class);

But I'm always getting null.

Why? How could I obtain the underlying connection?

UPDATE:

After changing the datasource definition it started to work. I remove a line of my datasource definition and it started to work. The line I've removed was

<driver-class>oracle.jdbc.OracleDriver</driver-class>

My datasource definion is:

<datasource jta="true" jndi-name="java:/jboss/datasources/Unificado" pool-name="Unificado" enabled="true" use-ccm="true">
      <connection-url>jdbc:oracle:thin:@10.12.54.186:1522:prd</connection-url>                    
      <driver>ojdbc6</driver>
      <security>
         <user-name>unificado</user-name>
         <password>*******</password>
      </security>
      <validation>                        
         <validate-on-match>false</validate-on-match>
         <background-validation>false</background-validation>
      </validation>
      <statement>
         <share-prepared-statements>false</share-prepared-statements>
      </statement>
</datasource>

Upvotes: 2

Views: 15892

Answers (3)

Roberto Petrilli
Roberto Petrilli

Reputation: 865

I've used

    //... some insert and update on EntityManager
    SessionImplementor sessionImp = (SessionImplementor) em.getDelegate();
    Connection con = sessionImp.connection();

to get JDBC connection as suggested in other answers but in my case I had also to flush the entity manager

    em.flush();

in order to "see" in my selects all the entities previously persisted both using em and repositories.

Upvotes: 0

Davide Consonni
Davide Consonni

Reputation: 2124

valid only for Spring framework

inject:

@PersistenceContext
private EntityManager entityManager;

and get connection using:

    EntityManagerFactoryInfo info = (EntityManagerFactoryInfo) entityManager.getEntityManagerFactory();
    Connection connection = info.getDataSource().getConnection();

Upvotes: 4

Md. Sajedul Karim
Md. Sajedul Karim

Reputation: 7095

You can get connection using bellow way:

Session session = entityManager.unwrap(Session.class);
session.doWork(connection -> doSomeStuffWith(connection));

How you get EntityManager?

@PersistenceContext
private EntityManager entityManager;

Here is the imports:

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.hibernate.Session;

Now, if you have problem on connection pooling then check this tread

Hope this will help you.

Thanks :)

Upvotes: 1

Related Questions