0

I am beginner with Java and Spring Boot, I use Pagination on Spring Boot, with this code I return the list of users, which I must if I want to also return the number of pages?

I know that with getTotalPages() I can get the page count but how to return it?

@Service
public class UserService{

    @Autowired
    UserRepository userRepository;

    public List<UserDto> findAll(PageRequest pageRequest){
        Page<User> userPage = userRepository.findAll(pageRequest);
        List<UserDTO> dtos = new ArrayList<UserDTO>();
        //return userPage.getContent();

        for (User u : userPage.toList() ) {
            dtos.add(new UserDTO(u));
        }
        return dtos;
    }
}
İsmail Y.
  • 3,579
  • 5
  • 21
  • 29
dev
  • 45
  • 6
  • Why don't you return the Page object, if you need the information that is stored in it? You can, of course, create a new class that contains a list of Users plus the number of pages, but that's basically... a simplified Page. – Florian Schaetz Mar 26 '22 at 12:17

1 Answers1

1

The most common implementation of the Page interface is provided by the PageImpl class, you can use like this:

import org.springframework.data.domain.PageImpl;

...
Page<UserDTO> pageResult = new PageImpl<>(dtos, 
        userPage.getPageable(), 
        userPage.getTotalElements());
return pageResult;

If you want, you can also use the .map() function of page result, it can be preferred according to the approach. https://stackoverflow.com/a/39037297/2039546

İsmail Y.
  • 3,579
  • 5
  • 21
  • 29