Micronaut MongoDB Synchronous

Learn how to use a blocking MongoClient with a Micronaut application

Authors: Sergio del Amo

Micronaut Version: 3.2.7

1. Getting Started

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

You will use MongoDB for persistence.

2. What you will need

To complete this guide, you will need the following:

  • Some time on your hands

  • A decent text editor or IDE

  • JDK 1.8 or greater installed with JAVA_HOME configured appropriately

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

4. Writing the App

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

mn create-app \
    --features=mongo-sync,graalvm example.micronaut.micronautguide \
    --build=gradle \
    --lang=java
If you don’t specify the --build argument, Gradle is used as the build tool.
If you don’t specify the --lang argument, Java is used as the language.

If you use Micronaut Launch, select Micronaut Application as application type and add the mongo-sync feature.

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

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.

4.1. POJO

Create Fruit POJO:

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

import io.micronaut.core.annotation.Creator;
import io.micronaut.core.annotation.Introspected;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.core.annotation.Nullable;
import org.bson.codecs.pojo.annotations.BsonCreator;
import org.bson.codecs.pojo.annotations.BsonProperty;

import javax.validation.constraints.NotBlank;

@Introspected (1)
public class Fruit {

    @NonNull
    @NotBlank (2)
    @BsonProperty("name") (3)
    private final String name;

    @Nullable
    @BsonProperty("description") (3)
    private String description;

    public Fruit(@NonNull String name) {
        this(name, null);
    }

    @Creator (4)
    @BsonCreator(3)
    public Fruit(@NonNull @BsonProperty("name") String name,  (3)
                 @Nullable @BsonProperty("description") String description) {  (3)
        this.name = name;
        this.description = description;
    }

    @NonNull
    public String getName() {
        return name;
    }

    @Nullable
    public String getDescription() {
        return description;
    }
}
1 Annotate the class with @Introspected to generate BeanIntrospection metadata at compilation time. This information can be used, for example, to the render the POJO as JSON using Jackson without using reflection.
2 Use javax.validation.constraints Constraints to ensure the data matches your expectations.
3 Since the POJO does not have an empty constructor, use the annotations @BsonCreator and BsonProperty to define data conversion between BSON and POJO with the MongoDB Java driver. See POJOs without No-Argument Constructor.
4 Annotate with @Creator to provide a hint as to which constructor is the primary constructor.

4.2. Repository

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

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

import io.micronaut.core.annotation.NonNull;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Iterator;
import java.util.List;

public interface FruitRepository {
    @NonNull
    List<Fruit> list();

    void save(@NonNull @NotNull @Valid Fruit fruit); (1)
}
1 Add @Valid to any method parameter which requires validation.

4.3. Controller

Create FruitController:

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

import io.micronaut.core.annotation.NonNull;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Post;
import io.micronaut.http.annotation.Status;
import io.micronaut.scheduling.TaskExecutors;
import io.micronaut.scheduling.annotation.ExecuteOn;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

@Controller("/fruits") (1)
@ExecuteOn(TaskExecutors.IO)  (2)
public class FruitController {

    private final FruitRepository fruitService;

    public FruitController(FruitRepository fruitService) {  (3)
        this.fruitService = fruitService;
    }

    @Get  (4)
    public List<Fruit> list() {
        return fruitService.list();
    }

    @Post (5)
    @Status(HttpStatus.CREATED) (6)
    public void save(@NonNull @NotNull @Valid Fruit fruit) { (7)
        fruitService.save(fruit);
    }
}
1 The class is defined as a controller with the @Controller annotation mapped to the path /fruits
2 It is critical that any blocking I/O operations (such as fetching the data from the database) are offloaded to a separate thread pool that does not block the Event loop.
3 Use constructor injection to inject a bean of type FruitRepository
4 The @Get annotation maps the list method to an HTTP GET request on /fruits
5 The @Post annotation maps the save method to an HTTP POST request on /fruits
6 You can return void in your controller’s method and specify the HTTP status code via the @Status annotation.
7 Add @Valid to any method parameter which requires validation.

4.4. Configuration

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

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

import io.micronaut.context.annotation.ConfigurationProperties;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.core.naming.Named;

@ConfigurationProperties("db") (1)
public interface MongoDbConfiguration extends Named {
    @NonNull
    String getCollection();
}
1 The @ConfigurationProperties annotation takes the configuration prefix

Define the values via configuration:

src/main/resources/application.yml
db:
  name: 'fruit'
  collection: 'fruit'

4.5. MongoDB repository

Implement FruitRepository by using a MongoDbClient

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

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import io.micronaut.core.annotation.NonNull;
import jakarta.inject.Singleton;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

@Singleton (1)
public class MongoDbFruitRepository implements FruitRepository {

    private final MongoDbConfiguration mongoConf;
    private final MongoClient mongoClient;

    public MongoDbFruitRepository(MongoDbConfiguration mongoConf,  (2)
                                  MongoClient mongoClient) {  (3)
        this.mongoConf = mongoConf;
        this.mongoClient = mongoClient;
    }

    @Override
    public void save(@NonNull @NotNull @Valid Fruit fruit){
        getCollection().insertOne(fruit);
    }

    @Override
    @NonNull
    public List<Fruit> list() {
        return getCollection().find().into(new ArrayList<>());
    }
    
    @NonNull
    private MongoCollection<Fruit> getCollection(){
        return mongoClient.getDatabase(mongoConf.getName())
                .getCollection(mongoConf.getCollection(), Fruit.class);
    }
}
1 Use jakarta.inject.Singleton to designate a class as a singleton.
2 Use constructor injection to inject a bean of type MongoDbConfiguration
3 Use constructor injection to inject a bean of type MongoDbClient

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

build.gradle
implementation("io.micronaut.mongodb:micronaut-mongo-sync")

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

4.6. Test

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

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 javax.validation.Valid;
import javax.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 the feature mongo-sync, the application includes the following test dependencies:

build.gradle
testImplementation("org.testcontainers:junit-jupiter")
testImplementation("org.testcontainers:mongodb")
testImplementation("org.testcontainers:testcontainers")

We use Testcontainers MongoDB Module to test the application.

Create a class to ease the start-up and shutdown of MongoDb with TestContainers.

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

import org.testcontainers.containers.MongoDBContainer;
import org.testcontainers.utility.DockerImageName;

public class MongoDbUtils {
    static MongoDBContainer mongoDBContainer;

    public static void startMongoDb() {
        if (mongoDBContainer == null) {
            mongoDBContainer = new MongoDBContainer(DockerImageName.parse("mongo:4.0.10"))
                    .withExposedPorts(27017);
        }
        if (!mongoDBContainer.isRunning()) {
            mongoDBContainer.start();
        }
    }

    public static String getMongoDbUri() {
        if (mongoDBContainer == null || !mongoDBContainer.isRunning()) {
            startMongoDb();
        }
        return mongoDBContainer.getReplicaSetUrl();
    }

    public static void closeMongoDb() {
        if (mongoDBContainer != null) {
            mongoDBContainer.close();
        }
    }
}

Create a test:

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

import io.micronaut.http.HttpStatus;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import io.micronaut.test.support.TestPropertyProvider;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;

@MicronautTest
@TestInstance(Lifecycle.PER_CLASS)
public class FruitControllerTest implements TestPropertyProvider {

    @Test
    void fruitsEndpointInteractsWithMongo(FruitClient fruitClient) {
        List<Fruit> fruits = fruitClient.findAll();
        assertTrue(fruits.isEmpty());

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

        assertEquals(HttpStatus.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(HttpStatus.CREATED, status);
        fruits = fruitClient.findAll();
        assertTrue(fruits.stream()
                .filter(f -> f.getDescription() != null && f.getDescription().equals("Keeps the doctor away"))
                .findFirst()
                .isPresent());
    }

    @AfterAll
    static void cleanup() {
        MongoDbUtils.closeMongoDb();
    }

    @Override
    public Map<String, String> getProperties() {
        MongoDbUtils.startMongoDb();
        return Collections.singletonMap("mongodb.uri", MongoDbUtils.getMongoDbUri());
    }
}

5. Testing the Application

To run the tests:

./gradlew test

Then open build/reports/tests/test/index.html in a browser to see the results.

6. Start MongoDB via Docker

You can run MongoDb via Docker:

docker run -ti --rm -p 27017:27017 mongo:4.0

The application connects to MongoDb, run via Docker, thanks to the following configuration:

src/main/resources/application.yml
mongodb:
  uri: mongodb://${MONGO_HOST:localhost}:${MONGO_PORT:27017}

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

8. Generate a Micronaut Application Native Image with GraalVM

We will use GraalVM, the polyglot embeddable virtual machine, to generate a native image of our Micronaut application.

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

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

8.1. Native image generation

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

Java 11
$ sdk install java 21.3.0.r11-grl
If you still use Java 8, use the JDK11 version of GraalVM.
Java 17
$ sdk install java 21.3.0.r17-grl

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

After installing GraalVM, install the native-image component, which is not installed by default:

gu install native-image

To generate a native image using Gradle, run:

./gradlew nativeCompile

The native image is created in build/native/nativeCompile directory and can be run with build/native/nativeCompile/application.

It is possible to customize the name of the native image or pass additional parameters to GraalVM:

build.gradle
graalvmNative {
    binaries {
        main {
            imageName.set('mn-graalvm-application') (1)
            buildArgs.add('--verbose') (2)
        }
    }
}
1 The native image name will now be mn-graalvm-application
2 It is possible to pass extra arguments to build the native image

Consume the endpoints exposed by the native image 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"}]

9. Next steps

Explore more features with Micronaut Guides.

10. Next Steps

11. Help with the Micronaut Framework

Object Computing, Inc. (OCI) sponsored the creation of this Guide. A variety of consulting and support services are available.