73

I have a List of entities. How do I convert it to Page Object using Spring MVC 4 and Spring Data JPA?

briantaurostack7
  • 1,193
  • 2
  • 14
  • 36

7 Answers7

133

There is a Page implementation for that:

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

There is one more Constructor :

Page<Something> page = new PageImpl<>(listOfsomething, pageable, listOfsomething.size());
Mehraj Malik
  • 14,872
  • 15
  • 58
  • 85
  • 10
    Here is how to create the `pageable` object: `Pageable pageable = PageRequest.of(pageNumber, size);` Note that `pageNumber` is *zero-based* and that `Pageable` and `PageRequest` are imported from `org.springframework.data.domain`. For more info, see [Pageable documentation](https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/domain/Pageable.html) – Aleksandar Jun 25 '18 at 10:12
  • @Mehraj Malik mine is not working with this ... https://stackoverflow.com/questions/62485592/pageable-in-spring-for-paging-on-listobject-is-not-working – dhS Jun 20 '20 at 13:46
8

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
);
smndiaye
  • 438
  • 7
  • 13
3

Normally, controller should receive a Pageable object as parameter. The Pageable object contains page number, page size and sorting information.

Then you can query all entities from JpaRepository with sorting and generate Page object:

List<Entity> allList = jpaRepository.findAll(pageable.getSort());

List<Entity> pageList = allList.stream()
    .skip(pageable.getOffset())
    .limit(pageable.getPageSize())
    .collect(Collectors.toList());

return new PageImpl<>(pageList, pageable, allList.size());

zhezha
  • 61
  • 5
2

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());
    }
davimargelo
  • 124
  • 6
1

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;
}
fall
  • 984
  • 11
  • 33
0
public static <T> PageData buildCustomPagedData(List<T> data, Pageable pageable) {
    List<T> model = new ArrayList<>();
    int start = VALUE_ZERO;
    if (!Objects.equals(pageable.getPageNumber(), FIRST_INDEX)) {
        start = (pageable.getPageNumber() * pageable.getPageSize());
    }
    for (int i = start; i < start + pageable.getPageSize(); i++) {
        if (i < data.size()) {
            model.add(data.get(i));
        } else {
            break;
        }
    }
    return PageData.builder()
            .model(model)
            .totalElements(data.size())
            .currentPage(pageable.getPageNumber() + INT_ONE)
            .totalPages((data.size() / pageable.getPageSize()) + INT_ONE)
            .build();
}
Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36