session.connection() deprecated on Hibernate?

Viewed 89683

We need to be able to get the associated java.sql.Connection of a hibernate session. No other connection will work, as this connection may be associated with a running transaction.

If session.connection() is now deprecated, how am I supposed to do that?

13 Answers

Here is a Java 8 method to return the Connection used by an EntityManager without actually doing anything with it yet:

private Connection getConnection(EntityManager em) throws SQLException {
    AtomicReference<Connection> atomicReference = new AtomicReference<Connection>();
    final Session session = em.unwrap(Session.class);
    session.doWork(connection -> atomicReference.set(connection));
    return atomicReference.get();
}
Related