我正在分页上并尝试为发送带有URL的firstResult和MaxResults的每个Rest api调用获取行数,对于命名约定,我已经将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:如果我愿意对代码进行任何改进,请多多关照

最佳答案

我认为您不能以这种方式使用它。之前,我总是使用两个单独的条件,一个用于列表,另一个用于计数。

然后,我再也不会在标准计数中配置分页。让我告诉你怎么做:

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();


这样,您检索计数行的条件不受分页的影响,这是不希望的。它运作良好。

希望能帮助到你!

07-27 16:06