快速后续请求后,Hibernate会话关闭异常 [英] Hibernate Session Closed Exception after fast subsequent requests

查看:135
本文介绍了快速后续请求后,Hibernate会话关闭异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个原因是:org.hibernate.SessionException:Session被关闭!当我在加载整个页面之前点击链接时发生错误(或者我的猜测,只是在活动的hibernate会话中)。

I get a Caused by: org.hibernate.SessionException: Session is closed! error when I click on a link before the whole page is loaded (or my guess, just inside the active hibernate session).

我的所有DAO类都是子类 GenericDAO

All of my DAO classes are subclassing GenericDAO where i got this method:

public Session getSession() {
    if (session == null || !session.isOpen()) {
        session = HibernateUtil.getSessionFactory().getCurrentSession();
    }
    return session;
}

这是从

This is called from:

public void beginTransaction() {
    transaction = getSession().beginTransaction();
}

并最终提交:

and finally commited:

public void commit() {
    if (transaction != null)
        transaction.commit();
    transaction = null;
    session = null;
}

我在这里错过了什么?

推荐答案

它看起来像你所有的请求使用你的DAO的单个实例。但是,您的DAO尝试在其字段中存储当前的 Session ,因此它无法处理并发请求。请注意, Session 不是线程安全的,您应该为不同的请求使用不同的 Session 。

It looks like you use a single instance of your DAO for all requests. However, your DAO tries to store the current Session in its field, therefore it cannot handle concurrent requests. Note that Session is not thread-safe and you should use different Sessions for different requests.

实际上,您不需要 getSession()方法中的复杂逻辑。当你在DAO中需要当前 Session 时,你可以写 sessionFactory.getCurrentSession()。只要Hibernate配置正确(参见 2.3。上下文会话),它将返回当前会话的正确实例,并且您的DAO将能够提供并发查询。

Actually, your complex logic in getSession() method is not needed. When you need a current Session in your DAO, you can just write sessionFactory.getCurrentSession(). As long as Hibernate is properly configured (see 2.3. Contextual sessions), it will return the correct instance of the current session, and your DAO will be able to serve concurrent queries.

这篇关于快速后续请求后,Hibernate会话关闭异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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