I've my PageableResponseModel
class:
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Getter
@Setter
public class PageableResponseModel<T> {
private static final Integer DEFAULT_PAGE_SIZE = 10;
private Long totalResults;
private Integer page;
private Integer size;
private List<T> results;
public Integer getSize() {
return
Objects.nonNull(size)
? size
: DEFAULT_PAGE_SIZE;
}
public void setSize(Integer size) {
this.size =
Objects.nonNull(size)
? size
: DEFAULT_PAGE_SIZE;
}
}
From my repositories, I'm getting org.springframework.data.domain.Page<T>
:
Uni<Page<T>> findAll(Specification<T> spec, Pageable pageable);
I need to convert from org.springframework.data.domain.Page<T>
to my PageableResponseModel<T>
.
Any ideas?
CodePudding user response:
I would add private constructor, setting the fields by invoking the API provided by Page and its' superinterface Slice. And public static fromPage
method to handle corner cases, nulls, etc.
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Getter
@Setter
public class PageableResponseModel<T> {
private static final Integer DEFAULT_PAGE_SIZE = 10;
private Long totalResults;
private Integer page;
private Integer size;
private List<T> results;
//getters and setters omitted
private PageableResponseModel(Page<T> page) {
this.totalResults = page.getTotalElements();
this.page = page.getNumber();
this.size = page.getSize();
this.results = page.getContent();
}
public static <R> PageableResponseModel<R> fromPage(Page<R> page) {
if (page == null) {
//some handling for your use case
return new PageableResponseModel<>(Page.empty());
}
return new PageableResponseModel<>(page);
}
}
CodePudding user response:
Create a constructor for PageableResponseModel
public PageableResponseModel(List<T> results, Integer page, Integer size, Long totalResults) {
this.content = content;
this.page = page;
this.size = size;
this.totalElements = totalElements;
}
Now in your service layer, first you need to check if the retrieved Page<T>
has any elements or not. If it is empty, you can return a new object of
return new PageableResponseModel<>(Collections.emptyList(), page.getNumber(),
page.getSize(), page.getTotalElements());
Else, you get the list from the Page<T>
using stream
and map
and feed the constructor like this
return new PageableResponseModel<>(list, page.getNumber(), page.getSize(), page.getTotalElements());