关闭打开的休眠会话(如果存在) [英] Close Opened Hibernation sessions if exist

查看:94
本文介绍了关闭打开的休眠会话(如果存在)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



(假设当一个 JFrame 关闭时,如果打开的会话可用,它们必须关闭。关闭会话可以通过遍历代码来完成一个,但我的意思是在这里,没有检查代码,是否有任何方法来关闭那些错过了一段代码关闭的会话)。

解决方案

div>

当数据库操作完成时,为什么不关闭会话?
我的意思是,在DAO类中你打开会话执行数据库操作。并在最后阻止,关闭你的会话。
您可以关闭会话:

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


$ / code $ / pre
$ b $ / $

您可以使用

  Session sess = sessionFactory.getCurrentSession(); 

并关闭JFrame关闭事件的会话。



我从这个链接


这里的主要契约是创建Session实例。通常
应用程序具有一个SessionFactory实例,并且线程
服务于客户端请求,从该工厂获取Session实例。
SessionFactory的内部状态是不可变的。一旦它创建了
,就设置了这个内部状态。这个内部状态包括关于对象/关系映射的元数据的所有

执行者必须是线程安全的。


完成操作或事务时关闭会话是我们的职责。当我们关闭sessionfactory时,所有资源(连接池等)都会正确释放。


When a Hibernate session is opened (sessionFactory.openSession()) it might be closed. It is ok. In case it is missed to close an opened session which is used to retrieve data (not to save or update or delete) any where in the application, how to close opened sessions if exists?

(Let's say when a JFrame is closed, if there are opened sessions available, they must be closed. Closing sessions can be done by going through the codes one by one, but I mean here, without checking codes, is there any way to close sessions which are missed to close with some piece of code).

解决方案

Why dont you close the session when your database operation finished? I mean, In DAO classes you get opened session perform database operation. And in finally block, Close your session. You can close session like :

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

OR

You can get the current session using

Session sess = sessionFactory.getCurrentSession();

And close session on closing event of JFrame.

I get following lines from 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.

And it is our duty to close session when finished the operation or transaction. When we close sessionfactory all resources(connection pools etc) are released properly.

这篇关于关闭打开的休眠会话(如果存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆