Skip to content
Advertisement

How to set TotalPages of a PageImpl class in spring boot

I’m converting a Page to a new one by using PageImpl class, but the totalpages attribute has the default value 0. I would like to set totalPages to a specific number. Is it possible to change it?

code

    public Page<InformationDTO> getInformationById(String classId, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        List<Information> InformationList = informationRepository.findByClassIdOrderByCreateDateDesc(classId, pageable).getContent();
        List<InformationDTO> InformationDTOList = new ArrayList<>();
        if(!InformationList.isEmpty()){
            for (Information information: informationList){
                informationDTOList.add(new InformationDTO(information));
            }
        }
        return new PageImpl<InformationDTO>(informationDTOList,pageable,informationList.size());
    }

Advertisement

Answer

To get a page as an answer you need to change a line in your code

// Earlier
List<Information> InformationList = informationRepository.findByClassIdOrderByCreateDateDesc(classId, pageable).getContent();

// Changed line
Page<Information> InformationList = informationRepository.findByClassIdOrderByCreateDateDesc(classId, pageable);


// Then you will not be required to explicitly change into pageable
PageImpl<InformationDTO>(informationDTOList,pageable,informationList.size());

Case 1 To find maximum pages

InformationList.getTotalPages()

Case 2 – Your scenario – From a collection object If want data with pagination then you have to take the help from PageImpl class.

which offer 2 Constructor to do this

PageImpl(List<T> content, Pageable pageable, long total)

where

  1. content – the content of this page(Your collection object).
  2. pageable – the paging information
  3. total – the total amount of items available.

There is also another constructor

PageImpl(List<T> content)

Note – This will result in the created Page being identical to the entire List.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement