53

I want to get jdbc connection from hibernate session.There is method inside hibernate session i.e session.connection(); but it has been deprecated. i know this works still but i dont want to use deprecated method as i am sure they must have provide some alternative for this? At http://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/Session.html connection method api says using org.hibernate.jdbc.Work for this purpose but i dont find any example for that?

1
  • 3
    If anyone marks a question as a duplicate please include a link to one of the other questions that already has an answer, Commented Oct 1, 2015 at 9:15

3 Answers 3

97

Here is how you can use it:

session.doWork(new Work() {
    @Override
    public void execute(Connection connection) throws SQLException {
        //connection, finally!
    }
});
8
  • Question: I get doWork is not valid without active transaction with this code, how to I start a transaction?
    – OscarRyz
    Commented Dec 6, 2012 at 20:52
  • 2
    @OscarRyz: if you are using Spring, @Transactional or TransactionTemplate is enough. In raw Hibernate you must run session.beginTransaction() manually. Commented Dec 6, 2012 at 20:55
  • Hi Buddy.. Nice answer but doWork() is also deprecated now.
    – Logicalj
    Commented Jan 9, 2013 at 10:33
  • 2
    @Logicalj: can you provide some reference? It's still valid in 4.1... Commented Jan 9, 2013 at 11:14
  • 5
    also worth to mention, there is a doReturningWork(...) method if you want to return a result.
    – Chris
    Commented Apr 30, 2014 at 16:55
30

Try this:

((SessionImpl)getSession()).connection()
2
  • 11
    To anyone who gets here unwarned (just like me): the Session.connection method is currently deprecated.
    – Dinei
    Commented Jun 13, 2015 at 21:20
  • 5
    never cast to an Impl! its internal! (org.hibernate.internal.SessionImpl). And you cannot test this code with a mock anymore. This is bad for many reasons.
    – Rainer
    Commented Jun 27, 2016 at 17:16
12

I had a similar Problem and I used the ConnectionProvider class to get the connection. See my solution:

Session session = entityManager.unwrap(Session.class);
SessionFactoryImplementor sessionFactoryImplementation = (SessionFactoryImplementor) session.getSessionFactory();
ConnectionProvider connectionProvider = sessionFactoryImplementation.getConnectionProvider();
try {
       connection = connectionProvider.getConnection();
       ...
}
3
  • 1
    Can you add a brief explanation of how this solves the problem?
    – Ren
    Commented Apr 26, 2013 at 11:23
  • 8
    sessionFactoryImplementation.getConnectionProvider() is depricated
    – vels4j
    Commented Feb 18, 2015 at 17:41
  • I cannot see that method in Hibernate 5.2.9 Commented Jun 16, 2020 at 8:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.