【问题标题】:Spring Data Pagination returns wrong number of content as it is requestedSpring Data Pagination 在请求时返回错误数量的内容
【发布时间】:2018-12-31 03:05:00
【问题描述】:

目前我正在开发一个使用Spring Data Pagination 的api,我遇到的问题是我将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());
}

【问题讨论】:

  • and size is 2 is pageable request...正如您在屏幕截图中看到的,我要求的是 2,而不是 3...
  • 您的分页文件没有用。您的查询方法是转换为查询,它总是会选择前 30 个。因此,您在分页中给出的限制不会被考虑在内。
  • @M.Deinum 为什么没用?
  • 因为在您的查询中您总是选择 30。
  • @M.Deinum 但为什么呢?

标签: java spring pagination spring-data-jpa


【解决方案1】:

试试:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-05
    • 2020-06-07
    • 2015-11-02
    • 2020-11-14
    相关资源
    最近更新 更多