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;
}
}
CodePudding user response:
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