How to implement pagination in Java (not using Spring framework)?

Is there a java example for Pagination similar to the one below?

The application i’m building is architected as:
Web page → On-load calls a service to fetch data (Angular) ← Service returns data (Java, jax-rs) <–> Connects to MongoDB (local, open-source)

Wanted to implement the fetch on backend/java-service, and allowing the frontend to send the offset and page-number.

Here is a post to start with: Paging with the Bucket Pattern - Part 1.

I also, suggest do a general search (i.e., Google, etc.) with the string “mongodb java pagination” where you get few articles / posts discussing some scenaios, opinions and solutions. It is likely, you will find a suitable answer for your specific need. Hope this is useful.

Here’s an example that worked for me:

public String fetchData(int offset, int page) {
    final String uriString = "mongodb://$[username]:$[password]@$[hostlist]/$[database]?authSource=$[authSource]";
    MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
    MongoDatabase database = mongoClient.getDatabase("airbnb");
    MongoCollection<Document> sampleDataCollection = database.getCollection("sample");

    List<Document> sampleDataList = sampleDataCollection.find()
            .skip( page > 0 ? ( ( page - 1 ) * offset ) : 0 )
            .limit(offset)
            .into(new ArrayList<>());

    System.out.println("\n\nTotal rows = " + sampleDataList.size());

    return gsonObj.toJson(sampleDataList);
}

Caller…

@Path("/airbnb-sample")
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getAirbnbSampleData(@QueryParam("offset") int offset, @QueryParam("page") int page) {
   return mongodbService.fetchData(offset, page);
}

REST call…

http://localhost:9191/mongodb/airbnb-sample-search?offset=50&page=2

I will add the full example on Github soon!

1 Like