为什么Spring Pageable返回意外结果?

时间:2018-11-21 17:37:49

标签: java spring-data-jpa

在数据库表products中,我有12条记录。 ID从1到12。我使用扩展了PagingAndSortingRepository的JpaRepository调用db。无法理解:

  1. 为什么Pageable不返回预期结果(大小)?

  2. 我也无法获得ID为1的产品。为什么会发生?

  3. 为什么pageble不是从id:1,然后2等开始?

请告知。

API /getPageable/{page}/{size}

我打电话给/getPageable/1/10并获得2 elements的列表。

我打电话给/getPageable/1/9并得到3 elements

/getPageable/1/8 - 4 elements ids: 10, 11, 12, 5 
/getPageable/1/7 - 5 elements ids: 9, 10, 11, 12, 5 
/getPageable/1/6 - 6 elements ids: 8, 9, 10, 11, 12, 5 
/getPageable/1/5 - 5 elements ids: 7, 8, 9, 10, 11 
/getPageable/1/4 - 4 elements ids: 6, 7, 8, 9 
/getPageable/1/3 - 3 elements ids: 4, 6, 7 
/getPageable/1/2 - 2 elements ids: 3, 4 
/getPageable/1/1 - 1 element id:2

/getPageable/2/1 - 1 element id: 3
/getPageable/2/2 - 2 elements ids: 6, 7
/getPageable/2/3 - 3 elements ids: 8, 9, 10
/getPageable/2/4 - 4 elements ids: 10, 11, 12, 5
/getPageable/2/5 - 2 elements ids: 12, 5
/getPageable/2/6 - 0 elements
/getPageable/2/7 - 0 elements
/getPageable/2/8 - 0 elements

控制器代码:

 @GET
        @Path("/getPageable/{pageId}/{size}")
        @Produces({"application/json"})
        @ApiOperation(value = "Get randomly list of products")
        @ApiResponses(value = {
                @ApiResponse(code = 200, message = "OK"),
                @ApiResponse(code = 500, message = "Something wrong in Server")})
        @ApiImplicitParams({
                @ApiImplicitParam(name = "X-Auth-Token", value = "Authorization token", required = true, dataType = "string", paramType = "header")
        })
        public List<Product> getProductsRandomly(@PathParam("pageId") Integer pageId, @PathParam("size") Integer size) {

            Pageable pageable = new PageRequest(pageId, size);

            return  productDao.findPageable(pageable).getContent();
        }

productDao

@Repository
public class ProductDao extends BaseDao<Product, Integer> {

    @Autowired
    private ProductRepository productRepository;
....
}

productResopitory

public interface ProductRepository extends JpaRepository<Product, Integer> {
...
}

JpaRepository extends PagingAndSortingRepository具有方法Page<T> findAll(Pageable var1);

1 个答案:

答案 0 :(得分:1)

尝试将pageId减1。数据库也从0开始索引。

        Pageable pageable = new PageRequest(pageId-1, size);