Spring中List到Page的转换

2022-01-18 00:00:00 list spring pagination java spring-data

我正在尝试在春季将列表转换为页面.我已经使用

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

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

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.

我的控制器

    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);
}

这是我的用户回购

public interface UserRepo extends JpaRepository<User, Integer>{

public List<User> findAllByProgramId(Integer programId);

这是我的服务

    public List<User> findAllByProgramId(Integer programId);

推荐答案

我也遇到了同样的问题.我使用了子列表:

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());

相关文章