Kest

Search

Search the documentation

Data

Pagination

Page, slice and sort results safely.

Never return a whole table. Ask for one page:

val page: Page<Order> = orders.findAll(PageRequest.of(1, 20, Sort.by("createdAt").descending()))
page.items         // the 20 orders
page.total         // how many exist in all
page.pages         // 8
page.hasNext       // true

Pages count from 1, so page = 1 is the first page. PageRequest.of(page, size, sort); size must be 1 or more.

Repository methods

MethodReturns
findAll(pageable)Page<T>: items, page, size, total, pages, hasNext, hasPrevious
findAll(sort)all rows, ordered
findPage(query, pageable, args...)a page of the rows matching a Query
findSlice(query, pageable, args...)Slice<T>: items and hasNext, no COUNT query (cheaper; for "load more")

Derived finders

Add a Pageable as the last parameter. The return type decides what you get:

interface OrderRepository : CrudRepository<Order, String> {
    fun findByStatus(status: String, pageable: Pageable): Page<Order>            // page + total
    fun findByCustomerId(id: String, pageable: Pageable): Slice<Order>           // no total
    fun findByTotalGreaterThan(min: Long, pageable: Pageable): List<Order>      // just this page's rows
    fun findByStatus(status: String, sort: Sort): List<Order>                    // ordering only
}

The Pageable and Sort are not query arguments: findByStatus(status, pageable) still means status = ?. A page's sort replaces the method's own OrderBy.

What the framework does for you

  • Stable order. The id is always added as the last sort key, so rows that tie on the sort column (many orders in the same second) are never repeated or skipped between pages.
  • Safe sorting. A sort property must be a stored property of the entity; anything else (name; drop table x, a relation, a typo) throws InvalidPagingException, which the HTTP layer answers with 400. Column names come from the entity, never from the request text.
  • No wasted COUNT. A short, non-empty page is the last page, so the total is offset + rows without counting. An empty first page is total 0.
  • Soft-deleted rows (@DeleteDate) are left out of items and totals.
  • Works the same on PostgreSQL, MySQL and MongoDB.

From an HTTP request

@Paged turns ?page=2&size=20&sort=name,-createdAt into a Pageable:

@Controller("/orders")
class OrdersController(private val orders: OrderRepository) {
    @Get fun list(@Paged(defaultSize = 20, maxSize = 100, sortable = ["createdAt", "total"], defaultSort = "-createdAt") page: Pageable): Page<Order> =
        orders.findAll(page)
 
    @Get("/open") fun open(@Paged page: Pageable) = orders.findByStatus("open", page)
}

GET /orders?page=2&size=20&sort=-total returns:

{ "items": [ ... ], "page": 2, "size": 20, "total": 143, "pages": 8, "hasNext": true, "hasPrevious": true }

A page below 1, a size of 0 or above maxSize, a non-number, or a sort outside sortable is a 400 with the reason. Sort syntax: name, -name (descending), name:desc, several joined by commas or repeated.

Limits of page numbers

Offset paging reads and discards the skipped rows, so very deep pages (page 50 000 of a large table) get slow. For feeds that people scroll through, use Slice (no COUNT) or cursor paging.

Cursor (keyset) paging

A cursor says "give me the rows after this one", so every page costs the same however deep you are, and rows added or removed between requests are never repeated or skipped:

var page = orders.findCursor(Query.ALL, sort = "createdAt", descending = true, after = null, size = 50)
page.items            // the first 50
page.nextCursor       // an opaque string, or null on the last page
page = orders.findCursor(Query.ALL, "createdAt", true, page.nextCursor, 50)      // the next 50

Send nextCursor to the client and take it back as ?after=.... The sort property must be a stored property that is never null (the id is added as a tie-breaker). It works on PostgreSQL, MySQL and MongoDB. CursorPage has items, size, nextCursor and hasNext.

Typed queries with paging

orders.queryPage(PageRequest.of(1, 20)) { where(Order::status eq "open") } and querySlice(...) combine the typed query DSL with paging.

Read more