【问题标题】:Creating a Spring Data Page from a simple collection从一个简单的集合创建一个 Spring Data Page
【发布时间】:2021-09-21 17:02:12
【问题描述】:

是否有允许从 Java 集合开始创建 Page 实例的 Spring 实用程序?

类似:

Page<MyObject> myObjPage = PagingUtils.createPageFromCollection(listOfMyObjects, pageable);

还是应该手动实现分页和排序逻辑?

【问题讨论】:

  • A Page 只是数据的持有者,它不进行分页和排序。这留给存储库来实现。为什么首先要将集合变成页面?
  • @M.Deinum 在我的项目中,该集合充当“表”,因此,我需要检索该集合中包含的内容的页面。
  • 然后您需要编写一个存储库,将您的集合作为表格处理并对其进行排序/分页。

标签: java spring spring-boot


【解决方案1】:

考虑两种情况-

  1. 我希望来自 spring 的数据作为分页和排序然后
    i) 创建一个排序对象(org.springframework.data.domain.Sort)
Sort sort = sortType.equals("ASC") ? Sort.by(sortField).ascending() :
                Sort.by(sortField).descending();

ii) 将此排序类型传递给可分页对象

Pageable pageable = PageRequest.of(pageId, pageSize, sort);

iii) 将此可分页对象传递给 JPArepository 方法

yourRepository.findAll(pageable);

这将返回带有分页和排序的数据。

案例 2 - 您的场景 - 从集合对象中我想要分页数据

那么你必须从 PageImpl 类中获得帮助。 它提供了 2 个构造函数来执行此操作

PageImpl(List<T> content, Pageable pageable, long total)

在哪里

  1. content – 此页面的内容(您的收藏对象)。
  2. pageable – 分页信息
  3. total – 可用项目的总量。

还有一个构造函数

PageImpl(List<T> content)

注意 - 这将导致创建的页面与整个列表相同。

【讨论】:

    【解决方案2】:

    Pageable pageable = PageRequest.of(pageNo-1, pageSize);

    Page page = questionRepository.findAll(pageable);

    列出问题 = page.getContent();

    【讨论】:

      【解决方案3】:

      我想你的问题可以用this link来回答。

      答案似乎你需要手动实现。

      【讨论】:

        猜你喜欢
        • 2021-12-24
        • 1970-01-01
        • 2019-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-02
        • 2022-01-28
        相关资源
        最近更新 更多