在Swing应用程序中使用Hibernate进行会话管理 [英] Session management using Hibernate in a Swing application

查看:177
本文介绍了在Swing应用程序中使用Hibernate进行会话管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Java Desktop Swing应用程序中执行Hibernate会话管理?你使用单个会话吗?多个工作阶段?

How do you do your Hibernate session management in a Java Desktop Swing application? Do you use a single session? Multiple sessions?

这里有几个参考资料:

  • http://www.hibernate.org/333.html
  • http://blog.schauderhaft.de/2008/09/28/hibernate-sessions-in-two-tier-rich-client-applications/
  • http://in.relation.to/Bloggers/HibernateAndSwingDemoApp

推荐答案

单个会话。当你需要做一组操作时(比如对话框中的OK按钮后更新数据)启动事务,提交tx结束。连接虽然是不断打开的(因为它是同一个会话),因此所有的缓存机会可以由Hib和RDBMS使用。

Single session. Start transaction when you need to do a set of operations (like update data after dialog box OK button), commit the tx at the end. The connection though is constantly open (since it's the same session), and thus all opportunities for caching can be used by both Hib and RDBMS.

它也可能是一个好想要实现透明会话重新打开以防万一连接死了 - 用户往往会让应用程序打开较长的时间,并且应该继续工作星期一,即使DB服务器在周末重新启动。

It may also be a good idea to implement a transparent session re-open in case the connection went dead -- users tend to leave applications open for extended periods of time, and it should continue to work Monday even if DB server was rebooted on weekend.

更新

Jens Schauder提供了使用多个工作阶段的原因:会话。嗯,这归结为你使用Hibernate的方式。

Jens Schauder provided a reason to use multiple sessions: partial (unwanted) updates to the session. Well, that comes down to the way you use Hibernate.

假设我们打开了两个对话框(如在Jens的博客示例中)。如果用户点击收音机框,我们会立即更新与此收音机相关联的Hibernate实体,那么当用户点击取消时,我们遇到了问题 - 会话已更新。

Suppose we have two dialogs open (as in Jens' blog example). If user clicks a radiobox, and we immediately update a Hibernate entity associated with this radiobox, then, when user clicks Cancel, we're in trouble -- session is already updated.

正如我看到的,正确的方式是只更新对话框变量(非Hibernate对象)。然后,当用户单击确定时,我们开始一个事务,合并更新的对象,提交事务。没有垃圾被保存到会话中。

The right way, as I see it, is to update dialog variables (non-Hibernate objects) only. Then, when user clicks OK, we begin a transaction, merge updated objects, commit the transaction. No garbage gets ever saved into session.

MyHibernateUtils.begin();
Settings settings = DaoSettings.load();
// update setttings here
DaoSettings.save(settings);
MyHibernateUtils.commit(); 

如果我们实现这样一个干净的分离关系,我们可以稍后切换到多个会话,

If we implement such a clean separation of concerns, we can later switch to multiple sessions with a simple change of MyHibernateUtils.begin() implementation.

对于可能的内存泄漏,well ... Transaction.commit()调用Session.flush(),AFAIK,清除缓存。此外,可以通过调用Session.setCacheMode()手动控制缓存策略。

As for possible memory leak, well... Transaction.commit() calls Session.flush(), which AFAIK, cleans the cache too. Also, one may manually control the caching policy by calling Session.setCacheMode().

这篇关于在Swing应用程序中使用Hibernate进行会话管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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