Search code examples
springhibernatejpaspring-data-jpaentitymanager

Spring Data JPA, how to get Connection used by the current transaction context


How do I get the java.sql.Connection used by the current transaction context? Or is the connection actually opened at the end of transaction?


Solution

  • Inject the entityManager then retrieve the current hibernate session

    Session session = (Session) entityManager.getDelegate();
    

    Then retrieve the jdbc connection from the session.

    By using the doWork function you can actually retrieve the connection

    session.doWork(new Work() {
        @Override
        public void execute(Connection connectionToUse) throws SQLException {
        }
    });