用Java Hibernate进行会话管理 [英] Session Management with Java Hibernate

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

问题描述

我有一个基于Hibernate的平台,由无状态的servlet构建(一个用于注册用户,其余的用于查询数据库)。



我是使用Hibernate的会话如下:

 会话会话= HibernateUtil.getSessionFactory()。getCurrentSession(); $(b)if((null == session)||(session.isOpen()== false)){
session = HibernateUtil.getSessionFactory()。openSession();
}

目前,我不会在servlet结束时关闭会话,以便避免 openSession()调用(如果可能的话,尝试使用打开的会话)。

最佳实践是什么?什么时候我应该关闭这些会议?



你能举个例子吗?



预先感谢!

解决方案

最佳做法是在大多数情况下按会话请求。也就是说,在处理请求开始时打开一个会话,最后关闭它。例如,您可以在Servlet Filter 中执行此操作。



整个应用程序有一个会话很糟糕,因为它会在第一级缓存中积累大量实体,这是内存泄漏。当多个客户同时使用它时,它也可能产生不确定的结果。



然而,你的代码并没有为整个应用程序使用一个会话 - 它使用当前会话的概念,它打开一个会话并将其存储在上下文中(例如, ThreadLocal )。但如果你不关闭它,它会永远呆在那里。另外,它会导致与上述相同的问题,因为线程在Web应用程序中被重用,并且新的请求会在某个时间点得到一个旧的未关闭的会话。


I have a Hibernate-based platform, built from stateless servlets (one is used to register a user and the rest to query the db).

I'm using Hibernate's sessions as follows:

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
if ((null == session) || (session.isOpen() == false)) {
  session = HibernateUtil.getSessionFactory().openSession();
}

Currently I do not close the session at the end of the servlet in order to avoid openSession() call (trying to use opened sessions if possible).

What's the best practice ? when am I supposed to close these sessions ?

Can you please give an example ?

Thanks in advance !

解决方案

The best practice is in most cases session-per-request. That is, open a session in the beginning of handling a request, and close it in the end. You can do that in a Servlet Filter, for example.

Having one session for the entire application is bad, because it will accumulate a lot of entities in its 1st level cache, which is a memory leak. It may also produce undeterministic results when multiple clients use it at the same time.

Your code, however, is not using one session for the entire application - it is using the "current session" concept, which opens a session and stores it in a context (a ThreadLocal for example). But if you don't close it, it will stay there forever. Plus, it will cause the same problems as described above, because threads are reused in a web application, and a new request will get an old, unclosed session at some point.

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

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