IllegalStateException: Session/EntityManager is closed

Viewed 1436

I'm trying to implement his Java code with Hibernate in order to make SQL queries:

public List<AttendeeModel> getListOfCds(int firstRow, int rowCount) {
        List<AttendeeModel> cdList = null;
        try {
            session.beginTransaction();
            Criteria criteria = session.createCriteria(AttendeeModel.class);
            criteria.setFirstResult(firstRow);
            criteria.setMaxResults(rowCount);
            if (criteria != null) {
                cdList = (List<AttendeeModel>) criteria.list();
            }
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            session.getTransaction().rollback();
        }
        return cdList;
    }

    public int countRows() {
        try {
            session.beginTransaction();
            Criteria criteria = session.createCriteria(AttendeeModel.class);
            if (criteria != null) {
                return criteria.list().size();
            }
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            session.getTransaction().rollback();
        }
        return 0;
    }

But for some reason I get this error:

 java.lang.IllegalStateException: Session/EntityManager is closed

Do you know how I can fix this issue?

1 Answers

From your code it is unclear where session is decleared and how it is populated. Given that this is done somehow correctly, I suspect that missing transaction commit/rollback before return in countRow leads to the exception, try:

public int countRows() {
    int size = 0;
    try {
        session.beginTransaction();
        Criteria criteria = session.createCriteria(AttendeeModel.class);
        if (criteria != null) {
            size = criteria.list().size();
        }
        session.getTransaction().commit();
    } catch (Exception e) {
        e.printStackTrace();
        session.getTransaction().rollback();
    }
    return size;
}
Related