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. This comment has been removed by a blog administrator.

    ReplyDelete
  3. I think this is the best article today. Thanks for taking your own time to discuss this topic, I feel happy about that curiosity has increased to learn more about this topic. Keep sharing your information regularly for my future reference.
    Java Courses in chennai

    ReplyDelete