Java / Maven

Micronaut MongoDB Synchronous

Learn how to use a blocking MongoClient with a Micronaut application

Sergio del Amo
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=mongo-sync,serialization-bson,serialization-jackson,graalvm \
    --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 mongo-sync, serialization-bson, serialization-jackson, and graalvm 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.

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

Controller

Create FruitController:

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

Configuration

Create a configuration object to encapsulate the MongoDB database name and collection name.

java/src/main/java/example/micronaut/MongoDbConfiguration.java

Define the values via configuration:

src/main/resources/application.properties
db.name=fruit
db.collection=fruit

MongoDB repository

Implement FruitRepository by using a MongoDbClient.

java/src/main/java/example/micronaut/MongoDbFruitRepository.java

By using the feature mongo-sync, the application includes the following dependency:

pom.xml
<dependency>
    <groupId>io.micronaut.mongodb</groupId>
    <artifactId>micronaut-mongo-sync</artifactId>
    <scope>compile</scope>
</dependency>

This registers a blocking MongoClient, which you can inject in other Micronaut beans as illustrated in the above code sample.

Test

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.core.annotation.NonNull;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Post;
import io.micronaut.http.client.annotation.Client;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import java.util.List;

@Client("/fruits")
public interface FruitClient {

    @Post
    @NonNull
    HttpStatus save(@NonNull @NotNull @Valid Fruit fruit);

    @NonNull
    @Get
    List<Fruit> findAll();
}

By using Test Resources, the application includes the following test dependencies:

pom.xml
<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>testcontainers-junit-jupiter</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>testcontainers-mongodb</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>testcontainers</artifactId>
    <scope>test</scope>
</dependency>

Test Resources will provide us with a MongoDB instance for local testing and execution.

Create a test:

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

import io.micronaut.http.HttpStatus;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import static io.micronaut.http.HttpStatus.CREATED;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;

@MicronautTest
public class FruitControllerTest {

    @Inject
    FruitClient fruitClient;

    @Test
    void fruitsEndpointInteractsWithMongo() {

        List<Fruit> fruits = fruitClient.findAll();
        assertTrue(fruits.isEmpty());

        HttpStatus status = fruitClient.save(new Fruit("banana"));
        assertEquals(CREATED, status);

        fruits = fruitClient.findAll();
        assertFalse(fruits.isEmpty());
        assertEquals("banana", fruits.get(0).getName());
        assertNull(fruits.get(0).getDescription());

        status = fruitClient.save(new Fruit("Apple", "Keeps the doctor away"));
        assertEquals(CREATED, status);

        fruits = fruitClient.findAll();
        assertTrue(fruits.stream().anyMatch(f -> "Keeps the doctor away".equals(f.getDescription())));
    }
}

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"}]

Generate a Micronaut Application Native Executable with GraalVM

We will use GraalVM, an advanced JDK with ahead-of-time Native Image compilation, to generate a native executable of this Micronaut application.

Compiling Micronaut applications ahead of time with GraalVM significantly improves startup time and reduces the memory footprint of JVM-based applications.

Note
Only Java and Kotlin projects support using GraalVM’s native-image tool. Groovy relies heavily on reflection, which is only partially supported by GraalVM.

GraalVM Installation

The easiest way to install GraalVM on Linux or Mac is to use SDKMan.io.

Java 25
sdk install java 25.0.2-graal

For installation on Windows, or for a manual installation on Linux or Mac, see the GraalVM Getting Started documentation.

The previous command installs Oracle GraalVM, which is free to use in production and free to redistribute, at no cost, under the GraalVM Free Terms and Conditions.

Alternatively, you can use the GraalVM Community Edition:

Java 25
sdk install java 25.0.2-graalce

Native Executable Generation

To generate a native executable using Maven, run:

./mvnw package -Dpackaging=native-image

The native executable is created in the target directory and can be run with target/micronautguide.

It is possible to customize the name of the native executable or pass additional build arguments using the Maven plugin for GraalVM Native Image building. Declare the plugin as follows:

pom.xml

Consume the endpoints exposed by the native executable with cURL:

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).