Access a MongoDB database asynchronously with Micronaut Data MongoDB and Reactive Streams
Learn how to access a MongoDB database asynchronously with Micronaut Data.
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:
-
Some time on your hands
-
A decent text editor or IDE (e.g. IntelliJ IDEA)
-
JDK 21 or greater installed with
JAVA_HOMEconfigured appropriately -
Docker installed to run MongoDB and to run tests using Testcontainers.
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.
-
Download and unzip the source
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=gradle \
--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:
annotationProcessor("io.micronaut.data:micronaut-data-document-processor")
implementation("io.micronaut.data:micronaut-data-mongodb")
runtimeOnly("org.mongodb:mongodb-driver-reactivestreams")
implementation("org.mongodb:mongodb-driver-reactivestreams")POJO
Create a Fruit POJO:
Repository
Create a repository interface to encapsulate the CRUD actions for Fruit.
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.
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.
Controller
Create FruitController:
Test Client
Add a Micronaut declarative HTTP Client to src/test to ease the testing of the application’s API.
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:
|
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:
And finally, create a test which uses a replacement FruitService to test the controller without touching the database:
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/databaseNameFor more information, see the MongoDB section of the Test Resources documentation.
Testing the Application
To run the tests:
./gradlew testThen open build/reports/tests/test/index.html in a browser to see the results.
Running the Application
To run the application, use the ./gradlew run command, which starts the application on port 8080.
curl -d '{"name":"Pear"}' \
-H "Content-Type: application/json" \
-X POST http://localhost:8080/fruitscurl -i localhost:8080/fruitsHTTP/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.
Read more about the integration between Micronaut Data and MongoDB.
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). |