Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Guide for the Cursor-based pagination #1463

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* Copyright 2017-2024 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.micronaut;

import io.micronaut.data.annotation.GeneratedValue;
import io.micronaut.data.annotation.Id;
import io.micronaut.data.annotation.MappedEntity;
import io.micronaut.serde.annotation.Serdeable;

@Serdeable // <1>
@MappedEntity // <2>
public record Fruit(@Id // <3>
@GeneratedValue // <4>
Long id,
String name) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
* Copyright 2017-2024 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.micronaut;

import io.micronaut.data.model.CursoredPage;
import io.micronaut.data.model.CursoredPageable;
import io.micronaut.data.model.Sort;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;

import java.util.ArrayList;
import java.util.List;

@Controller("/fruits") // <1>
class FruitController {

private static final Sort SORT = Sort.of(Sort.Order.asc("name"));

private final FruitRepository repository;

FruitController(FruitRepository repository) { // <2>
this.repository = repository;
}

@Get // <3>
List<Fruit> index() {
CursoredPage<Fruit> page = repository.find(CursoredPageable.from(2, SORT)); // <4>
List<Fruit> fruits = new ArrayList<>(page.getContent());
while (page.hasNext()) {
page = repository.find(page.nextPageable());
fruits.addAll(page.getContent());
}
return fruits;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
* Copyright 2017-2024 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.micronaut;

import io.micronaut.data.jdbc.annotation.JdbcRepository;
import io.micronaut.data.model.CursoredPage;
import io.micronaut.data.model.CursoredPageable;
import io.micronaut.data.model.query.builder.sql.Dialect;
import io.micronaut.data.repository.CrudRepository;

@JdbcRepository(dialect = Dialect.H2) // <1>
public interface FruitRepository extends CrudRepository<Fruit, Long> { // <2>

CursoredPage<Fruit> find(CursoredPageable pageable); // <3>
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
micronaut.application.name=micronautguide
#tag::datasource[]
datasources.default.password=
datasources.default.dialect=H2
datasources.default.schema-generate=CREATE_DROP
datasources.default.url=jdbc\:h2\:mem\:devDb;LOCK_TIMEOUT\=10000;DB_CLOSE_ON_EXIT\=FALSE
datasources.default.username=sa
datasources.default.driver-class-name=org.h2.Driver
#end::datasource[]
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
* Copyright 2017-2024 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.micronaut;

import io.micronaut.core.type.Argument;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.client.BlockingHttpClient;
import io.micronaut.http.client.HttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import org.junit.jupiter.api.Test;
import java.util.List;

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;

@MicronautTest(transactional = false) // <1>
class FruitControllerTest {

@Test
void itIsPossibleToNavigateWithCursoredPage(@Client("/") HttpClient httpClient, // <2>
FruitRepository repository) {
List<Fruit> data = List.of(
new Fruit(null, "apple"),
new Fruit(null, "banana"),
new Fruit(null, "cherry"),
new Fruit(null, "date"),
new Fruit(null, "elderberry"),
new Fruit(null, "fig"),
new Fruit(null, "grape"),
new Fruit(null, "honeydew"),
new Fruit(null, "kiwi"),
new Fruit(null, "lemon")
);
repository.saveAll(data);
int numberOfFruits = data.size();
assertEquals(numberOfFruits, repository.count());

BlockingHttpClient client = httpClient.toBlocking();
HttpResponse<List<Fruit>> response = assertDoesNotThrow(() ->
client.exchange(HttpRequest.GET("/fruits"), (Argument.listOf(Fruit.class))));
assertEquals(HttpStatus.OK, response.getStatus());
List<Fruit> fruits = response.body();
assertEquals(numberOfFruits, fruits.size());
repository.deleteAll();
}
}
15 changes: 15 additions & 0 deletions guides/micronaut-data-cursored-page/metadata.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"title": "Cursor-based pagination",
"intro": "Learn how to use Cursor-based pagination with Micronaut Data JDBC.",
"authors": ["Sergio del Amo"],
"tags": [],
"categories": ["Micronaut Data"],
"publicationDate": "2024-05-09",
"languages": ["java"],
"apps": [
{
"name": "default",
"features": ["data-jdbc", "h2"]
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
common:header.adoc[]

This guide uses Micronaut Data's https://micronaut-projects.github.io/micronaut-data/latest/guide/#cursored-pagination[Cursored Pagination] to traverse data.

Micronaut Data Cursor-page pagination is inspired by https://jakarta.ee/specifications/data/1.0/data-1.0.0-rc1#_cursor_based_pagination[Jakarta Data's Cursor-based pagination].
____
Cursor-based pagination aims to reduce missed and duplicate results across pages by querying relative to the observed values of entity properties that constitute the sorting criteria
____

common:requirements.adoc[]

common:completesolution.adoc[]

common:create-app.adoc[]

== Writing the Application

We will create a Micronaut Data JDBC with an H2 database application that exposes a REST API.

=== Data Source Dependencies

Add the following dependencies:

:dependencies:

dependency:micronaut-data-processor[groupId=io.micronaut.data,scope=annotationProcessor,callout=1]
dependency:micronaut-data-jdbc[groupId=io.micronaut.data,callout=2]
dependency:micronaut-jdbc-hikari[groupId=io.micronaut.sql,callout=3]
dependency:h2[groupId=com.h2database,scope=runtimeOnly,callout=4]

:dependencies:

<1> Configures Hibernate/JPA EntityManagerFactory beans.
<2> Adds Micronaut Data Transaction Hibernate dependency.
<3> Configures SQL DataSource instances using Hikari Connection Pool.
<4> Add dependency to in-memory H2 Database.

:dependencies:

And the database configuration:

resource:application.properties[tag=datasource]

== Writing the Application

=== Entities

Add the following entity:

source:Fruit[]

callout:serdeable[1]
callout:mapped-entity[2]
callout:mapped-entity-id[3]
callout:generated-value[4]

=== Repository

Add a repository interface. Micronaut Data provides an implementation of the interface at compilation time. You can use https://micronaut-projects.github.io/micronaut-data/latest/api/io/micronaut/data/model/CursoredPageable.html[CursoredPageable] as a method parameter and https://micronaut-projects.github.io/micronaut-data/latest/api/io/micronaut/data/model/CursoredPage.html[CursoredPage] as a return type.


source:FruitRepository[]

callout:jdbcrepository[1]
callout:crudrepository[2]
<3> The signature defines a https://micronaut-projects.github.io/micronaut-data/latest/api/io/micronaut/data/model/CursoredPageable.html[CursoredPageable] parameter and https://micronaut-projects.github.io/micronaut-data/latest/api/io/micronaut/data/model/CursoredPage.html[CursoredPage] return type.

=== Controller

Create a controller that uses the repository's method with Cursor Pagination capabilities.

source:FruitController[]

callout:controller[number=1,arg0=/fruits]
callout:constructor-di[number=2,arg0=FruitRepository]
callout:get-generic[number=3]
<4> The code uses `CursoredPage::hasNext` and `CursorPage::nextPageable` to traverse the data.

=== Tests

The following test verifies the controller fetches every entity.

test:FruitControllerTest[]

callout:micronaut-test-transactional-false[1]
callout:http-client[2]

== Next steps

Read more about https://micronaut-projects.github.io/micronaut-data/latest/guide/#cursored-pagination[Micronaut Data's Cursored Pagination] support.

common:helpWithMicronaut.adoc[]
Loading