首页 > 解决方案 > Spring Data Pagination 在请求时返回错误数量的内容

问题描述

目前我正在开发一个使用的api,Spring Data Pagination我遇到了一个问题,我将一个Pageable对象作为请求传递给我的存储库,我想要接收哪个页面以及应该有多少元素。有了这个我的对象看起来像:Pageable pageable = PageRequest.of(0, 2);- 所以我想要有两个元素的第一页。在我的数据库中有 3 个对象,因此将有 2 页。但是 ide 显示给我的是: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());
}

标签: javaspringpaginationspring-data-jpa

解决方案


尝试:

@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());
}

推荐阅读