在我的Spring Boot Rest Service中,我想使用分页实现getAll方法,以便稍后在前端进行延迟加载。
目前,如果我要第一组行,则必须请求第0页。在application.properties中插入以下配置后,它应该可以工作... spring.data.web.pageable.one-indexed-parameters = true ...但事实并非如此。
有人知道这是为什么还是传统的方法吗?我正在使用2.0.4.RELEASE版本中的spring-boot-starter-web和data-jpa。
非常感谢!
编辑,这是服务方法,也许PageRequest无法处理此问题。
public List<TransactionResponseDTO> findAll(int pageNumber, int pageSize) {
List<TransactionResponseDTO> transactionResponseDTOs = new ArrayList<>();
PageRequest pageRequest = PageRequest.of(pageNumber, pageSize);
List<TransactionEntity> transactionEntities =
transactionRepository.findAll(pageRequest).getContent();
for (TransactionEntity transactionEntity : transactionEntities) {
transactionResponseDTOs.add(convert(transactionEntity));
}
return transactionResponseDTOs;
}
答案 0 :(得分:1)
我认为那是臭虫。参见https://github.com/spring-projects/spring-boot/issues/14413
“ SpringDataWebAutoConfiguration”应位于“ RepositoryRestMvcAutoConfiguration”之前,这会使“ PageableHandlerMethodArgumentResolverCustomizer”无法正常工作,因此cofig yml的“ spring.data.web.pageable”无法正常工作
答案 1 :(得分:1)
属性 spring.data.web.pageable.one-indexed-parameters = true 仅控制如何将分页参数自动绑定到Web请求处理程序方法的 Pageable 的行为。 strong>论点。
情况1:,默认行为是 spring.data.web.pageable.one-indexed-parameters = false ,当使用进行请求时http://localhost:8080/api/customers? page = 5
@GetMapping("/api/customers")
public List<Customer> getCustomers(Pageable pageable) {
//here pageable.getPageNumber() == 5
Page<Customer> customersPage = customerRepository.findAll(pageable);
//here customersPage.getNumber() == 5
}
案例2:使用 spring.data.web.pageable.one-indexed-parameters = true 以及使用http://localhost:8080/api/customers?page=5发出请求时>
@GetMapping("/api/customers")
public List<Customer> getCustomers(Pageable pageable) {
//here pageable.getPageNumber() == 4
Page<Customer> customersPage = customerRepository.findAll(pageable);
//here customersPage.getNumber() == 4
}
请注意,一旦您获得数据 PagecustomersPage ,如果您选中 customersPage.getNumber(),它将仅返回 pageable.getPageNumber()中的内容。 ,它是4。使用基于1的索引,我们可能希望5个希望的单索引参数返回5,但事实并非如此。
答案 2 :(得分:0)
您需要为存储库添加分页支持,您需要扩展
PagingAndSortingRepository<T,ID>
界面而不是基本的
CrudRepository<T,ID>
界面。这会添加接受Pageable的方法,以控制返回结果的数量和页面。
public Page findAll(Pageable pageable);
在这里https://docs.spring.io/spring-data/rest/docs/2.0.0.M1/reference/html/paging-chapter.html
检查答案 3 :(得分:0)
@Configuration
public class PageableConfig {
@Bean
PageableHandlerMethodArgumentResolverCustomizer pageableResolverCustomizer() {
return pageableResolver -> pageableResolver.setOneIndexedParameters(true);
}
}