gpt4 book ai didi

java - 是否应该关闭从 hibernate session 获得的连接?

转载 作者:搜寻专家 更新时间:2023-11-01 02:26:53 25 4
gpt4 key购买 nike

我是否需要手动关闭从 hibernate session 获得的连接?

如果我这样做,我会关闭连接池中的连接之一吗?

如果我不关闭连接,hibernate 会自动关闭吗?

            Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;

String query = "sql query";
try {
Session session = this.sessionFactory.getCurrentSession();
con = session.connection();
ps = con.prepareStatement(query);
rs = ps.executeQuery();
while (rs.next()) {
//read result set
}
} catch (SQLException exp) {
log.error("Error: ", exp);
} finally{
if(ps != null)
ps.close();
if(con != null)
con.close(); //Is this required?
}

最佳答案

一般来说,您不应该关闭该连接。 hibernate session 可能仍希望在 session 生命周期的后期使用相同的连接对象执行其他任务,您将通过关闭其连接来中断这些任务。管理该连接对象的生命周期是 hibernate 的工作。

异常(exception)情况是 described in the javadoc ,如果您打开了 ConnectionReleaseMode.AFTER_STATEMENT 并且 JDBC 提供程序支持该模式。这种情况并不常见,因为您必须处于自动提交模式才能工作。

关于java - 是否应该关闭从 hibernate session 获得的连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20393230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com