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

7

79

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

Bloodhound answered 10/5, 2016 at 11:4 Comment(0)
S
139

There is a Page implementation for that:

final Page<Something> page = new PageImpl<>(theListOfSomething);
Sorehead answered 10/5, 2016 at 11:26 Comment(3)
it doesn't divide them into pages but returns all the items in one pagePlath
It Will have errorCorncob
This doesn't work for me. It gave me error 500 on SpringBoot. Then I tried @mehraj-malik solution below and it worked.Spital
D
65

There is one more Constructor :

Page<Something> page = new PageImpl<>(listOfsomething, pageable, listOfsomething.size());
Distrust answered 16/10, 2017 at 7:59 Comment(2)
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 documentationAerostat
@Mehraj Malik mine is not working with this ... #62486092Lacey
I
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
);
Idyll answered 15/11, 2019 at 2:33 Comment(0)
E
4

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

Easement answered 10/12, 2021 at 17:39 Comment(2)
You can use pageable.getOffset() for skipping, you don't need to multiplyViolation
Thanks @CptWasp, applied to the answer.Easement
Z
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());
    }
Zante answered 9/2, 2021 at 12:31 Comment(0)
M
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;
}
Mangum answered 7/4, 2021 at 9:27 Comment(0)
B
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();
}
Bard answered 9/11, 2022 at 4:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.