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?
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 Session
s 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