Spring Data Pagination返回错误的内容数量

时间:2018-12-30 12:02:24

标签: java spring pagination spring-data-jpa

当前,我正在开发一个使用Spring Data Pagination的api,但遇到一个问题,我将Pageable对象作为请求传递给我的存储库,我希望通过该对象接收哪个页面以及应该包含多少个元素在上面。这样,我的对象看起来像:Pageable pageable = PageRequest.of(0, 2);-所以我想要包含两个元素的首页。在我的数据库中有3个对象,因此将有2页。但是,想法向我展示的是:screenshot。谁能告诉我为什么它表明内容是3个元素的数组,但实际上我要2个元素?

   @Override
public List<NotificationDto> getLast30NotificationsFor(ApplicationUser user) {
    Pageable pageable = PageRequest.of(0, 2);
    Page<Notification> first30ByOwnerIdOrderByCreatedAtDesc = notificationRepository.findFirst30ByOwnerIdOrderByCreatedAtDesc(user.getId(), pageable);

    List<Notification> notifications = new ArrayList<>(first30ByOwnerIdOrderByCreatedAtDesc.getContent());
    return notifications.stream()
            .map(NotificationToDtoMapper::map)
            .collect(toList());
}

1 个答案:

答案 0 :(得分:0)

尝试:

@Override
public List<NotificationDto> getLast30NotificationsFor(ApplicationUser user) {
    Pageable page = PageRequest.of(0,2, Sort.by("createdAt").descending());
    return notificationRepository.findByOwnerId(user.getId(), page)
    .getContent()
    .stream()
    .map(NotificationToDtoMapper::map)
    .collect(toList());
}