我正在尝试使用Hibernate实现他的Java代码以进行SQL查询:
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;
}
但是由于某些原因,我会收到此错误:
java.lang.IllegalStateException: Session/EntityManager is closed
您知道如何解决此问题吗?
答案 0 :(得分:0)
从您的代码中,尚不清楚session
在何处被清除以及如何填充。鉴于此操作已正确完成,我怀疑在countRow返回之前缺少事务提交/回滚会导致异常,请尝试:
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;
}