Springboot JPA Pageable不适用于大于0的页码

时间:2017-01-17 20:50:01

标签: spring spring-data-jpa jpql

我想获得结果分页,如果请求是在页面参数设置为0的情况下进行的,则下面的代码可以正常工作,但它不适用于页面> 0,如page = 1或page = 2或page = 3等

这是我的RequestMapping

MyResponse getSample(@ModelAttribute MyRequest MyRequest) {
        Pageable pageRequest =  new PageRequest(MyRequest.page, MyRequest.size)
        MyModule.findSamples(MyRequest, pageRequest)
    }



class MyRequest {

    MyQueryType queryType


    String searchTerm


    @Min(value = 0L, message = 'Offset must be greater than or equal to 0')
    int offset = 0

    @Min(value = 0L, message = 'Offset must be greater than or equal to 0')
    int page = 0

    @Min(value = 1L, message = 'Limit must be greater than or equal to 1')
    int limit = 100

    @Min(value = 1L, message = 'Limit must be greater than or equal to 1')
    int size = 5
}


MyModule:Code inside my Module



MyResponse findSamples(MyRequest MyRequest, Pageable pageRequest) {
            log.info("Page Information Set "+pageRequest.pageNumber+pageRequest.pageSize)
            Page<SamplesPO> pages = null
            pages = MyRepository.findAllById(MyRequest.Id, pageRequest)
            } 

存储库代码:

public interface SampleRepository extends JpaRepository<Sample, Long> {

        @Query('''
        select e.Samples
        from ParentSampleTable e
        where e.Id = :Id
    ''')
    Page<Sample> findAllById(@Param('Id') String Id, Pageable pageRequest)
}

2 个答案:

答案 0 :(得分:0)

您可以尝试使用id

提取@PathParam

方法getSample使用@GetMapping注明(@PathParam("id") String id, Pageable pageable)并且可以返回sampleRepository.findAllById(id, pageable)

网址可能如下:/samples/id?page=pageNr&size=nrOfElemOnPage

您的存储库应该返回 Page<Sample> findAllById(String id, Pageable pageable)

另外,请在将代码发布到stackoverflow之前考虑重构(缩进)

这也可能是重复:Using findAll PagingAndSortingRepository with filter

答案 1 :(得分:0)

在使用以下代码之前,请阅读PageRequest java docs。页面请求  请求适用于页码(从索引0开始到1,2,3,依此类推  上)和大小(所需的限制)

Sort sort = new Sort(Sort.Direction.DESC, "mfgDate");

Pageable pageable = new PageRequest(pageNumber, pageSize, sort);

 @Repository
 public interface BikeRepository extends MongoRepository<Bike, String> {
        Page<Bike> findByCompanyId(String companyId, Pageable pageable);
    }