gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:54:27 26 4
gpt4 key购买 nike

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

  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

Controller 代码:

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

产品道

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

@Autowired
private ProductRepository productRepository;
....
}

产品资源库

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

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

最佳答案

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

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

关于java - 为什么 Spring Pageable 返回意外结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53417732/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com