views:

25

answers:

2

If I want to use SessionFactoryUtils to get Connection directly to execute some SQL statement, and join the same transaction. Like this:

SessionFactoryUtils.getDataSource(getSessionFactory()).getConnection();
//some logic after Connection retrieved

Do I have to close Connection by myself? or just let it be and Hibernate Session will handle it for me?

A: 

I think all you need to do is to handle your session properly (i.e. flush it, close it, whatever is valid for your setup).

But why not to use createSQLQuesry method of Session instead of getting direct connection?

Georgy Bolyuba
+1  A: 

If I want to use SessionFactoryUtils to get Connection directly to execute some SQL statement, and join the same transaction. (...) Do I have to close Connection by myself? or just let it be and Hibernate Session will handle it for me?

You are directly borrowing a connection from the pool here and there is no guarantee that a Session would get the same IMO. You are thus responsible for closing that connection properly and I'd suggest to use:

SessionFactoryUtils.getDataSource(getSessionFactory()).closeConnection(conn);

If you want to work with the connection managed by a Session, use Session#doWork(Work) (this new API replaces the old Session#connection() method which is deprecated and will be removed from Hibernate 4.x). In that case, the connection will be closed with the Session.

Or maybe just use Session#createSQLQuery(String) as already suggested.

Actually, providing more context information (are you in a template, do you already have a Session, will you get one, etc) would really help to find the best solution (it might not be the chosen one).

See also

Pascal Thivent