Spring数据Page.getTotalElements在最后一页上不正确

时间:2017-08-17 16:39:54

标签: java spring-boot spring-data

在最后一页上,PageImpl.getTotalElements没有返回正确的元素总数。

例如:

import java.util.Arrays;
import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

public class TestCaseGetTotalElements {

    public static void main(String[] args) {
        List<Integer> l = Arrays.asList(1, 2, 3);

        Page<Integer> firstpage = new PageImpl<>(l, new PageRequest(0, 2), l.size());
        Page<Integer> secondpage = new PageImpl<>(l, new PageRequest(1, 2), l.size());

        System.out.println("On First page, total is " + firstpage.getTotalElements()); 
        System.out.println("On Second page, total is "+ secondpage.getTotalElements());
    }
}

将输出:

On First page, total is 3
On Second page, total is 5

这是一个错误吗? 如果没有,如何获得正确的元素总数?

我使用spring-boot 1.5.4,这取决于spring-data-commons 1.13.4。

2 个答案:

答案 0 :(得分:2)

它确实打印了正确数量的元素。

在第二次通话中,您正在为PageImpl提供3个值,第1页和第2页。

So total elements = page 0(2) + (page 1(2) + 1) 
page 1(2) + 1 -- > 3 values 


/**
 * Constructor of {@code PageImpl}.
 * 
 * @param content the content of this page, must not be {@literal null}.
 * @param pageable the paging information, can be {@literal null}.
 * @param total the total amount of items available. The total might be adapted considering the length of the content
 *          given, if it is going to be the content of the last page. This is in place to mitigate inconsistencies
 */
public PageImpl(List<T> content, Pageable pageable, long total) {

    super(content, pageable);

    this.pageable = pageable;
    this.total = pageable.toOptional().filter(it -> !content.isEmpty())//
            .filter(it -> it.getOffset() + it.getPageSize() > total)//
            .map(it -> it.getOffset() + content.size())//
            .orElse(total);
}

答案 1 :(得分:0)

这是针对我的情况下相同错误的解决方案

int pageSize = pageable.getPageSize();
long pageOffset = pageable.getOffset();
long total = pageOffset + list.size() + (list.size() == pageSize ? pageSize : 0);
Page<listType> page = new PageImpl<listType>(list, pageable,total)