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);
Spring Data REST Pagination In Spring Data, if we need to return a few results from the complete data set, we can use any Pageable repository method, as it will always return a Page. The results will be returned based on the page number, page size, and sorting direction.
The most common way to create a Pageable instance is to use the PageRequest implementation: Pageable pageable = PageRequest. of(0, 5, Sort.by( Order. asc("name"), Order.
We can create a PageRequest object by passing in the requested page number and the page size. In Spring MVC, we can also choose to obtain the Pageable instance in our controller using Spring Data Web Support. The findAll(Pageable pageable) method by default returns a Page<T> object.
A page is a sublist of a list of objects. It allows gain information about the position of it in the containing entire list.
I had the same problem. I used subList:
final int start = (int)pageable.getOffset(); final int end = Math.min((start + pageable.getPageSize()), users.size()); final Page<User> page = new PageImpl<>(users.subList(start, end), pageable, users.size());
There is a Page
implementation for that:
Page<Something> page = new PageImpl<>(yourList);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With