PagingAndSortingRepository-自定义可分页的响应结构 [英] PagingAndSortingRepository - custom pageable response structure
问题描述
有没有一种方法可以简化从此控制器返回的结构:
Is there a way to simplify the structure returned from this controller:
@GetMapping
public Iterable<Task> getAll(@PathParam("page") int page) {
Pageable pageable = PageRequest.of(page, 3);
return taskRepository.findAll(pageable);
}
现在响应的主体如下:
localhost:8080 / api / task?page = 2
{
"content": [
...
],
"pageable": {
"sort": {
"sorted": false,
"unsorted": true,
"empty": true
},
"offset": 6,
"pageSize": 3,
"pageNumber": 2,
"paged": true,
"unpaged": false
},
"totalElements": 19,
"last": false,
"totalPages": 7,
"number": 2,
"size": 3,
"sort": {
"sorted": false,
"unsorted": true,
"empty": true
},
"numberOfElements": 3,
"first": false,
"empty": false
}
是否有任何方法可以减少此数据?如果我现在对排序不感兴趣,只想返回以下内容,该怎么办:
Is there any way to strip down on this data? What if I am not interested in sorting right now and only want to return something like this:
{
"content": [
...
],
"pageable": {
"pageSize": 3,
"pageNumber": 2,
"totalElements": 19,
},
}
所以当前响应太多我不需要的属性。什么是实现此目标的好方法?如果我想对其进行大量自定义,是否应该完全不同地执行此操作?
So the current response just has too many properties I don't really need. What is a good way to achieve this? Should I be doing this completely differently if I want to customize it so much?
推荐答案
另一种方法是创建自定义页面类根据需要并根据数据创建并返回
Another way is to create a custom page class as you want and create from your data and return
@Data
public class CustomPage<T> {
List<T> content;
CustomPageable pageable;
public CustomPage(Page<T> page) {
this.content = page.getContent();
this.pageable = new CustomPageable(page.getPageable().getPageNumber(),
page.getPageable().getPageSize(), page.getTotalElements());
}
@Data
class CustomPageable {
int pageNumber;
int pageSize;
long totalElements;
public CustomPageable(int pageNumber, int pageSize, long totalElements) {
this.pageNumber = pageNumber;
this.pageSize = pageSize;
this.totalElements = totalElements;
}
}
}
并像这样使用
@GetMapping
public CustomPage<Task> getAll(@PathParam("page") int page) {
Pageable pageable = PageRequest.of(page, 3);
return new CustomPage<Task>(taskRepository.findAll(pageable));
}
注意: 这里@Lombok的数据用于设置器吸气剂等。
这篇关于PagingAndSortingRepository-自定义可分页的响应结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!