我创建了自定义存储库,并希望创建自定义本机查询:
public Page<Friend> findFriends(FriendCriteria friendCriteria, Pageable pageable)
我该如何在其中放置Pageable对象并以Page <>对象的形式获取结果?
答案 0 :(得分:0)
我有类似的要求,但找不到任何直接方法。这是我如何实现的代码片段。希望这会有所帮助。
public Page<Friend> findFriends(FriendCriteria friendCriteria, Pageable pageable){
//Find actual content from friendCriteria and call method below.
extractPage(pageable, <actual content>);
}
public static <T> Page<T> extractPage(Pageable page, List<T> contents) {
int startIndex = page.getPageNumber() == 0 ? page.getPageNumber() : page.getPageNumber() + page.getPageSize();
int toIndex = startIndex + page.getPageSize();
toIndex = toIndex > contents.size() ? contents.size() : toIndex;
final int total = contents.size();
List<T> filteredContents;
if (startIndex < contents.size()) {
filteredContents = contents.subList(startIndex, toIndex);
} else {
filteredContents = new ArrayList<>();
}
TotalSupplier totalSupplier = () -> {
return total;
};
return PageableExecutionUtils.getPage(filteredContents, gotoPage(page.getPageNumber(), page.getPageSize()),
totalSupplier);
}
private static PageRequest gotoPage(int number, int size) {
return new PageRequest(number, size);
}