Hibernate标准,rowcount()仅适用于firstResult = 0

时间:2015-10-09 08:10:11

标签: java hibernate pagination hibernate-criteria

我正在进行分页并试图为每个使用url发送firstResult和MaxResults的Rest api调用获取rowcount,对于命名约定我已经提到firstResult作为pageNumber而MaxResults作为pageSize并且所需的代码片段看起来像这样,当pageNumber为1(FirstResult为0)resultCount获取正确的计数但当我传递大于1(FirstResult将为> 0)时,计数返回null:

    Criteria criteria = session().createCriteria(Manufacturer.class);
    criteria.add(Restrictions.eq("hospital.id", hospitalId));
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    // Implementing pagination
    if(pageNumber != null && pageSize != null){

        criteria.setFirstResult((pageNumber - 1) * pageSize);
        criteria.setMaxResults(pageSize);
    }

    List<Manufacturer> manufacturers = criteria.list();
    if(manufacturers == null || manufacturers.isEmpty()){
        return null;
    }

    // Reusing the same criteria for count
    criteria.setProjection(Projections.rowCount());
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    Long resultCount = (Long)criteria.uniqueResult();

P.S:如果代码中有任何改进的余地我会很感激

1 个答案:

答案 0 :(得分:3)

我认为你不能这样使用它。当我以前这样做时,我总是使用两个单独的标准,一个用于列表,另一个用于计数。

然后,我从未将分页配置为条件计数。让我告诉你如何:

private Criteria prepareCriteriaCommon(Integer hospitalId){
    Criteria criteria = session().createCriteria(Manufacturer.class);
    criteria.add(Restrictions.eq("hospital.id", hospitalId));
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    return criteria;
}

...

//Your sample code
Criteria crtList = prepareCriteriaCommon(hospitalId);
Criteria crtCount = prepareCriteriaCommon(hospitalId);

// Implementing pagination
if(pageNumber != null && pageSize != null){
    crtList.setFirstResult((pageNumber - 1) * pageSize);
    crtList.setMaxResults(pageSize);
}

List<Manufacturer> manufacturers = crtList.list();
if(manufacturers == null || manufacturers.isEmpty()){
    return null;
}

crtCount.setProjection(Projections.rowCount());
crtCount.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
Long resultCount = (Long)crtCount.uniqueResult();

这样,检索计数行的标准不受分页的影响,这是不可取的。效果很好。

希望它有所帮助!