首页 > 解决方案 > 使用 Java 时如何在 Spanner 中实现分页

问题描述

我有以下代码,其中有 200 条记录。我需要在此实现分页。

  Statement.Builder buildStatement = Statement.newBuilder(sql);
  List<EmployeeSpanner> spannerList= this.spannerTemplate
                .query(EmployeeSpanner.class, buildStatement.build(), null);

SQL 是基于多个逻辑和条件创建的,因此我不能使用类似findAll.

这将返回 200 条记录,我们需要通过分页将其发送到 UI,以便在第一页仅显示 25 条记录,在第二页显示 25 条,依此类推。

当为下面的 OLTP 完成此操作时,我们会这样做,但对于 Google 扳手,我需要类似的东西。

 int countset= (int) (pageable.getOffset() > countOfRecord? 0 : pageable.getOffset());
        query.setFirstResult(countset);
        query.setMaxResults(pageable.getPageSize());

    return new PageImpl<>(query.getResultList(), pageable, countOfRecord);

标签: javagoogle-cloud-spanner

解决方案


要实现分页查询,您需要SpannerQueryOptions使用 alimit和 anoffset进行配置,然后将其传递给查询。

SpannerQueryOptions spannerQueryOptions = new SpannerQueryOptions().setLimit(25L).setOffset(page * 25L);

Statement.Builder buildStatement = Statement.newBuilder(sql);
List<EmployeeSpanner> spannerList= this.spannerTemplate.query(EmployeeSpanner.class, buildStatement.build(), spannerQueryOptions);

推荐阅读