简体   繁体   English

使用SessionFactoryUtils时是否应该关闭连接

[英]Should I close connection when using SessionFactoryUtils

If I want to use SessionFactoryUtils to get Connection directly to execute some SQL statement, and join the same transaction. 如果我想使用SessionFactoryUtils直接获取Connection来执行一些SQL语句,并加入相同的事务。 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? 还是顺其自然,Hibernate Session会为我处理呢?

If I want to use SessionFactoryUtils to get Connection directly to execute some SQL statement, and join the same transaction. 如果我想使用SessionFactoryUtils直接获取Connection来执行一些SQL语句,并加入相同的事务。 (...) Do I have to close Connection by myself? (...)我必须自己关闭Connection吗? or just let it be and Hibernate Session will handle it for me? 还是顺其自然,Hibernate Session会为我处理呢?

You are directly borrowing a connection from the pool here and there is no guarantee that a Session would get the same IMO. 您是直接从此处的池借用连接的,因此不能保证Session将获得相同的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). 如果要使用由Session管理的连接,请使用Session#doWork(Work) (此新API取代了旧的Session#connection()方法,该方法已过时,将从Hibernate 4.x中删除)。 In that case, the connection will be closed with the Session . 在这种情况下, Session将关闭连接。

Or maybe just use Session#createSQLQuery(String) as already suggested. 或者,可以按照建议使用Session#createSQLQuery(String)

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). 实际上,提供更多的上下文信息(您是否在模板中,是否已经有一个Session,是否会获得一个会话等等)确实有助于找到最佳的解决方案(它可能不是所选择的)。

See also 也可以看看

I think all you need to do is to handle your session properly (ie flush it, close it, whatever is valid for your setup). 我认为您所需要做的就是正确处理会话(即刷新,关闭它,无论设置是否有效)。

But why not to use createSQLQuesry method of Session instead of getting direct connection? 但是,为什么不使用Session的createSQLQuesry方法代替直接连接呢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM