Conversion of List to Page in Spring

user3127109 picture user3127109 · Jun 10, 2016 · Viewed 89.6k times · Source

I am trying to convert list to page in spring. I have converted it using

new PageImpl(users, pageable, users.size());

But now I having problem with sorting and pagination itself. When I try passing size and page, the pagination doesn't work.

Here's the code I am using.

My Controller

    public ResponseEntity<User> getUsersByProgramId(
        @RequestParam(name = "programId", required = true) Integer programId Pageable pageable) {

    List<User> users = userService.findAllByProgramId(programId);
    Page<User> pages = new PageImpl<User>(users, pageable, users.size());

    return new ResponseEntity<>(pages, HttpStatus.OK);
}

Here is my user Repo

public interface UserRepo extends JpaRepository<User, Integer>{

public List<User> findAllByProgramId(Integer programId);

Here is my service

    public List<User> findAllByProgramId(Integer programId);

Answer

shilaimuslm picture shilaimuslm · Jun 12, 2016

I had the same problem. I used subList:

int start = pageable.getOffset();
int end = (start + pageable.getPageSize()) > users.size() ? users.size() : (start + pageable.getPageSize());
Page<User> pages = new PageImpl<User>(users.subList(start, end), pageable, users.size());