我正在使用Hibernate Criteria尝试实现分页,但是问题是,对于每个页面提取,我必须进行两个数据库调用,一个用于结果,另一个用于总记录数。有什么有效的方法,以便在一个数据库调用中我既可以获取数据,又可以减少数据库调用。
Criteria criteria=session.createCriteria(Student.class); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); criteria.add(Restrictions.ne("enquiryStatus", ENQUIRY.JOINED)); criteria.setMaxResults(10); criteria.setFirstResult((paginate.getStartIndex()-1)*10); criteria.setProjection(Projections.rowCount()); //here i need to fetch total row count and records
是的,您需要单独的查询来获取总结果计数。
Query aCountQuery = session.createQuery("select count(s.id) from Student s where s.enquiryStatus != :enquiryStatus"); aCountQuery.setParameter("enquiryStatus", ENQUIRY.JOINED); Long resultCount = (Long)aCountQuery.uniqueResult();
要么
Criteria criteria=session.createCriteria(Student.class); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); criteria.add(Restrictions.ne("enquiryStatus", ENQUIRY.JOINED)); criteria.setProjection(Projections.rowCount()) Long resultCount = (Long)criteria.uniqueResult();
更新资料
现在,您可以对分页和结果计数使用相同的条件
Criteria criteria=session.createCriteria(Student.class); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); criteria.add(Restrictions.ne("enquiryStatus", ENQUIRY.JOINED)); criteria.setMaxResults(10); criteria.setFirstResult((paginate.getStartIndex()-1)*10); List<Student> students = criteria.list(); criteria.setProjection(null); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); Long resultCount = (Long)criteria.uniqueResult();