Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion of List to Page in Spring

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); 
like image 225
user3127109 Avatar asked Jun 10 '16 13:06

user3127109


People also ask

How does Spring Pageable work?

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.

How do I create a spring boot page?

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.

How do you make an object Pageable?

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.

What is Page in Java?

A page is a sublist of a list of objects. It allows gain information about the position of it in the containing entire list.


2 Answers

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()); 
like image 110
shilaimuslm Avatar answered Oct 03 '22 09:10

shilaimuslm


There is a Page implementation for that:

Page<Something> page = new PageImpl<>(yourList); 
like image 28
Sachin Gaur Avatar answered Oct 03 '22 11:10

Sachin Gaur