How to convert a list of enity object to page object in Spring MVC (JPA)?

Solution 1:

There is a Page implementation for that:

final Page<Something> page = new PageImpl<>(theListOfSomething);

Solution 2:

There is one more Constructor :

Page<Something> page = new PageImpl<>(listOfsomething, pageable, listOfsomething.size());

Solution 3:

I think you will need to fetch the correct page content as well.


PageRequest pageRequest = PageRequest.of(offset, limit);

List<Product> products = getProducts();

int total = products.size();
int start = toIntExact(pageRequest.getOffset());
int end = Math.min((start + pageRequest.getPageSize()), total);

List<Product> output = new ArrayList<>();

if (start <= end) {
    output = products.subList(start, end);
}

return new PageImpl<>(
    output,
    pageRequest,
    total
);

Solution 4:

You can pass a list to the function to make it a pageable object. If the start value of the sublist is less than the list size, it returns the empty content.

  public Page<?> toPage(List<?> list, Pageable pageable) {
        int start = (int) pageable.getOffset();
        int end = Math.min((start + pageable.getPageSize()), list.size());
        if(start > list.size())
            return new PageImpl<>(new ArrayList<>(), pageable, list.size());
        return new PageImpl<>(list.subList(start, end), pageable, list.size());
    }

Solution 5:

The above answers all assume the list is what you wish to return. Here is what you can do to perform pagination on a list containing total records.

//pageNum starts with 1
//size: page size
//totalRecords, total records
Page<Record> myMethod(int pageNum, int size, List<MyRecord> totalRecords){
    if(pageNum<1){
        pageNum = 1;
    }
    if(size < 1){
        size = 10;
    }
    //spring page starts with 0
    Pageable pageable = new PageRequest(pageNum-1, size);
    //when pageNum * size is too big(bigger than list.size()), totalRecords.subList() will throw a exception, we need to fix this
    if(pageable.getOffset() > list.size()){
            pageable = new PageRequest(0, size);
    }
    List<MyRecord> pageRecords = totalRecords.subList(pageable.getOffset(), Math.min(pageable.getOffset() + pageable.getPageSize(), totalRecords.size()));
    
    Page springPage = new PageImpl<>(pageRecords, pageable, totalRecords.size());
    return springPage;
}