在Spring中将列表转换为页面
我试图在spring将列表转换为页面。 我用它转换了它
new PageImpl(users,pageable,users.size());
但是现在我有排序和分页本身的问题。 当我尝试传递大小和页面时,分页不起作用。
这是我正在使用的代码。
我的控制器
public ResponseEntity getUsersByProgramId( @RequestParam(name = "programId", required = true) Integer programId Pageable pageable) { List users = userService.findAllByProgramId(programId); Page pages = new PageImpl(users, pageable, users.size()); return new ResponseEntity(pages, HttpStatus.OK); }
这是我的用户回购
public interface UserRepo extends JpaRepository{ public List findAllByProgramId(Integer programId);
这是我的服务
public List findAllByProgramId(Integer programId);
我遇到了同样的问题。 我使用subList解决了这个问题,即:
int start = pageable.getOffset(); int end = (start + pageable.getPageSize()) > users.size() ? users.size() : (start + pageable.getPageSize()); Page pages = new PageImpl (users.subList(start, end), pageable, users.size());
可能有点傻,希望可以帮到你。 🙂
如参考文档中所示 ,Spring Data存储库通过简单地声明Pageable
类型的参数来确保它们只读取所请求Page
所需的数据,从而支持对查询方法的分页。
Page page = findAllByProgramId(Integer programId, Pageable pageable);
这将返回一个Page
对象,其中包含Pageable
对象中定义的页面大小/设置。 无需获取列表,然后尝试创建一个页面。
您是否尝试将存储库扩展到PagingAndSortingRepository
?
public interface UserRepo extends PagingAndSortingRepository { Page findAllByProgramId(Integer programId, Pageable pageable); }
服务
Page findAllByProgramId(Integer programId, Pageable pageable);
我假设您正在使用该服务的接口:
//1) For a boot application create a paging repository interface public interface PersonRepository extends PagingAndSortingRepository { // Common CURD method are automatically implemented } //2) create a service Interface public interface PersonService { Page listAllByPage(Pageable pageable); // Use common CURD findAll() method Page
Try This: public Page searchPatientPage(SearchPatientDto patient, int page, int size){ List patientsList = new ArrayList (); Set list=searchPatient(patient); patientsList.addAll(list); int start = new PageRequest(page, size).getOffset(); int end = (start + new PageRequest(page, size).getPageSize()) > patientsList.size() ? patientsList.size() : (start + new PageRequest(page, size).getPageSize()); return new PageImpl (patientsList.subList(start, end), new PageRequest(page, size), patientsList.size()); }
有一个Page
实现 :
Page page = new PageImpl<>(yourList);
谢谢以下代码的人在我的情况下工作
int start = pageble.getOffset(); int end = (start + pageble.getPageSize()) > vehicleModelsList.size() ? vehicleModelsList.size() : (start + pageble.getPageSize());