Jun 14, 2013

Getting JDBC SQL Connection in JPA with Hibernate

When you need to retrieve the plain Connection from JPA, unfortunately, there is no JPA standard way (unless you get a configured datasource with JNDI). This is needed when you use libraries or legacy applications which use JDBC instead of JPA.


Hibernate 3.x and JPA 1.0

With Hibernate you can get the org.hibernate.session. In pre Hibernate 4.o there was the connection() method which now is removed.
EntityManager em = ...;
Session session = (Session) em.getDelegate();
Connection conn = session.connection();

Hibernate 3.x and JPA 2.0

EntityManager em = ...;
Connection conn = em.unwrap(Session.class).connection();

Hibernate 4.x and JPA 2.0

Session session = em.unwrap(Session.class);
SessionFactoryImplementor sfi = (SessionFactoryImplementor) session.getSessionFactory();
ConnectionProvider cp = sfi.getConnectionProvider();
Connection conn = cp.getConnection();

JNDI-Lookup

If you are running inside a container, you could also perform a JNDI lookup on the configured DataSource.

3 comments:

  1. all examples not working. I suggest this:
    public static Connection getConnection() {
    EntityManager em = ;
    Session ses = (Session) em.getDelegate();
    SessionFactoryImpl sessionFactory = (SessionFactoryImpl) ses.getSessionFactory();
    try{
    connection = sessionFactory.getConnectionProvider().getConnection();
    }catch(SQLException e){
    ErrorMsgDialog.getInstance().setException(e);
    }
    return connection;
    }

    ReplyDelete
  2. thanks Юрий Щербак , it works.

    ReplyDelete