Java / Maven

Access a MongoDB database asynchronously with Micronaut Data MongoDB and Reactive Streams

Learn how to access a MongoDB database asynchronously with Micronaut Data.

Tim Yates
On this guide
In this section

Getting Started

In this guide, we will create a Micronaut application written in Java.

You will use MongoDB for persistence.

What you will need

To complete this guide, you will need the following:

Solution

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.

Writing the Application

Create an application using the Micronaut Command Line Interface or with Micronaut Launch.

mn create-app example.micronaut.micronautguide \
    --features=data-mongodb-reactive,reactor \
    --build=maven \
    --lang=java \
    --test=junit
Note
If you don’t specify the --build argument, Gradle with the Kotlin DSL is used as the build tool.
If you don’t specify the --lang argument, Java is used as the language.
If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.

The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.

If you use Micronaut Launch, select Micronaut Application as application type and add data-mongodb-reactive, and reactor features.

Note
If you have an existing Micronaut application and want to add the functionality described here, you can view the dependency and configuration changes from the specified features, and apply those changes to your application.

Dependencies

In this guide, we use the MongoDB Reactive driver.

The data-mongodb-reactive feature adds the following dependencies:

pom.xml
<!-- Add the following to your annotationProcessorPaths element -->
<path>
    <groupId>io.micronaut.data</groupId>
    <artifactId>micronaut-data-document-processor</artifactId>
</path>
<dependency>
    <groupId>io.micronaut.data</groupId>
    <artifactId>micronaut-data-mongodb</artifactId>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver-reactivestreams</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver-reactivestreams</artifactId>
    <scope>compile</scope>
</dependency>

POJO

Create a Fruit POJO:

java/src/main/java/example/micronaut/Fruit.java

Repository

Create a repository interface to encapsulate the CRUD actions for Fruit.

java/src/main/java/example/micronaut/FruitRepository.java

Service

Create a service FruitService as an API to interact with the Fruit repository. This will allow you to keep business logic out of the controller, and to test the controller later without interacting with a real database.

java/src/main/java/example/micronaut/FruitService.java
package example.micronaut;

import io.micronaut.core.annotation.NonNull;
import org.reactivestreams.Publisher;

import java.util.List;

interface FruitService {

    Publisher<Fruit> list();

    Publisher<Fruit> save(Fruit fruit);

    Publisher<Fruit> find(@NonNull String id);

    Publisher<Fruit> findByNameInList(List<String> name);
}

And then create a default implementation of this service.

java/src/main/java/example/micronaut/DefaultFruitService.java

Controller

Create FruitController:

java/src/main/java/example/micronaut/FruitController.java

Test Client

Add a Micronaut declarative HTTP Client to src/test to ease the testing of the application’s API.

java/src/test/java/example/micronaut/FruitClient.java
package example.micronaut;

import io.micronaut.http.HttpResponse;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.PathVariable;
import io.micronaut.http.annotation.Post;
import io.micronaut.http.annotation.Put;
import io.micronaut.http.annotation.QueryValue;
import io.micronaut.http.client.annotation.Client;
import jakarta.validation.constraints.NotNull;

import java.util.List;
import java.util.Optional;

@Client("/fruits")
interface FruitClient {

    @Get
    Iterable<Fruit> list();

    @Get("/{id}")
    Optional<Fruit> find(@PathVariable String id);

    @Get("/q")
    Iterable<Fruit> query(@QueryValue @NotNull List<String> names);

    @Post
    HttpResponse<Fruit> save(Fruit fruit);

    @Put
    Fruit update(Fruit fruit);
}

Then create a test that verifies the validation of the Fruit entity when we create a new entity via POST:

java/src/test/java/example/micronaut/FruitValidationControllerTest.java
Note
Transaction mode is not supported when the synchronous transaction manager is created using Reactive transaction manager!

Create a test that checks the controller works against a real MongoDB database:

java/src/test/java/example/micronaut/FruitControllerTest.java

And finally, create a test which uses a replacement FruitService to test the controller without touching the database:

java/src/test/java/example/micronaut/ControllerIsolationTest.java

Test Resources

When the application is started locally, either under test or while running locally, resolution of the property mongodb.uri is detected and the Test Resources service will start a local MongoDB docker container, and inject the properties required to use this as the datasource.

When running under production, you should replace this property with the location of your production MongoDB instance via an environment variable.

MONGODB_URI=mongodb://username:password@production-server:27017/databaseName

Testing the Application

To run the tests:

./mvnw test

Running the Application

To run the application, use the ./mvnw mn:run command, which starts the application on port 8080.

curl -d '{"name":"Pear"}' \
     -H "Content-Type: application/json" \
     -X POST http://localhost:8080/fruits
curl -i localhost:8080/fruits
HTTP/1.1 200 OK
date: Wed, 15 Sep 2021 12:40:15 GMT
Content-Type: application/json
content-length: 110
connection: keep-alive

[{"name":"Pear"}]

Next Steps

Explore more features with Micronaut Guides.

Help with the Micronaut Framework

The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.

License

Note
All guides are released with an Apache License 2.0 for the code and a Creative Commons Attribution 4.0 license for the writing and media (images).