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?
3 Answers
Here is how you can use it:
session.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
//connection, finally!
}
});
-
Question: I get
doWork is not valid without active transaction
with this code, how to I start a transaction?– OscarRyzCommented Dec 6, 2012 at 20:52 -
2@OscarRyz: if you are using Spring,
@Transactional
orTransactionTemplate
is enough. In raw Hibernate you must runsession.beginTransaction()
manually. Commented Dec 6, 2012 at 20:55 -
Hi Buddy.. Nice answer but doWork() is also deprecated now.– LogicaljCommented 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
-
5also worth to mention, there is a doReturningWork(...) method if you want to return a result.– ChrisCommented Apr 30, 2014 at 16:55
Try this:
((SessionImpl)getSession()).connection()
-
11To anyone who gets here unwarned (just like me): the
Session.connection
method is currently deprecated.– DineiCommented Jun 13, 2015 at 21:20 -
5never 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.– RainerCommented Jun 27, 2016 at 17:16
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();
...
}