Hibernate Session Closed Exception after fast subsequent requests

此生再无相见时 提交于 2019-12-08 04:05:45

问题


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).

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;
}

Am I missing something here?


回答1:


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.

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.



来源:https://stackoverflow.com/questions/8036947/hibernate-session-closed-exception-after-fast-subsequent-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!