hibernate中criteria 的Projections.rowCount()分页查询满足条件的总记要数注意的地方

hibernate中criteria 的Projections.rowCount()分页查询满足条件的总记录数注意的地方
public DataUtils queryByCriteria(Alsobuy alsobuy,int pagesize,int pageindex)
{
getSession();

DataUtils dataUtils=new DataUtils();

try {
Criteria criteria=session.createCriteria(Alsobuy.class);

Example example=Example.create(alsobuy);
example.excludeNone();
example.excludeZeroes();
example.ignoreCase();
example.enableLike(MatchMode.ANYWHERE);

criteria.add(example);
Integer total=(Integer)criteria.setProjection(Projections.rowCount()).uniqueResult();

criteria.setProjection(null);
criteria.setMaxResults(pagesize);
criteria.setFirstResult((pageindex-1)*pagesize);

dataUtils=new DataUtils(criteria.list(),total);

} catch (HibernateException e) {
e.printStackTrace();
}
finally
{
closeSession();
}
return dataUtils;
}


这里我采用 QBE(Example) 查询
注意Integer total=(Integer)criteria.setProjection(Projections.rowCount()).uniqueResult();的位置,它必须在以下三句代码的前面

criteria.setProjection(null);
criteria.setMaxResults(pagesize);
criteria.setFirstResult((pageindex-1)*pagesize);

否则查询不到记录为空null

criteria.setProjection(null);这句的作用是将原来设置Projection(投影,投影图)的清空,否则只能查到满足条件的总记录数而criteria.list()将没有记录。
1 楼 xile53 2011-11-29  
hibernate中criteria 的Projections.rowCount()分页查询满足条件的总记要数注意的地方
谢谢 !用到了
2 楼 lintghi 2012-05-22  
hibernate中criteria 的Projections.rowCount()分页查询满足条件的总记要数注意的地方