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
Sessionin its field, therefore it cannot handle concurrent requests. Note thatSessionis not thread-safe and you should use differentSessions for different requests.Actually, your complex logic in
getSession()method is not needed. When you need a currentSessionin your DAO, you can just writesessionFactory.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.