gpt4 book ai didi

java - 关闭打开的 hibernate session (如果存在)

转载 作者:行者123 更新时间:2023-11-29 06:05:59 25 4
gpt4 key购买 nike

当 Hibernate session 打开时 (sessionFactory.openSession()) 它可能会关闭。没关系。如果错过关闭用于在应用程序中任何位置检索数据(而不是保存或更新或删除)的已打开 session ,如何关闭已打开的 session (如果存在)?

(假设当 JFrame 关闭时,如果有打开的 session 可用,则必须关闭它们。关闭 session 可以通过一个一个地检查代码来完成,但我的意思是,在不检查代码的情况下,是否有任何方法可以关闭错过的某些代码段关闭的 session )。

最佳答案

为什么在数据库操作完成后不关闭 session ?我的意思是,在 DAO 类中,您打开 session 执行数据库操作。在 finally block 中,关闭您的 session 。您可以像这样关闭 session :

finally {
if(session!=null){
session.close();
}
}

您可以使用获取当前 session

Session sess = sessionFactory.getCurrentSession();

并在 JFrame 的关闭事件上关闭 session 。

我从 this link 得到以下几行

The main contract here is the creation of Session instances. Usually an application has a single SessionFactory instance and threads servicing client requests obtain Session instances from this factory. The internal state of a SessionFactory is immutable. Once it is created this internal state is set. This internal state includes all of the metadata about Object/Relational Mapping. Implementors must be threadsafe.

我们有责任在完成操作或交易后关闭 session 。当我们关闭 sessionfactory 时,所有资源(连接池等)都会正确释放。

关于java - 关闭打开的 hibernate session (如果存在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8523332/

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