Micronaut MongoDB Synchronous

Learn how to use a blocking MongoClient with a Micronaut application

Authors: Sergio del Amo

Micronaut Version: 4.4.0

1. Getting Started

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

You will use MongoDB for persistence.

2. What you will need

To complete this guide, you will need the following:

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 Application

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

mn create-app example.micronaut.micronautguide \
    --features=yaml,mongo-sync,graalvm,serialization-bson,serialization-jackson \
    --build=maven \
    --lang=kotlin \
    --test=junit
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 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 yaml, mongo-sync, graalvm, serialization-bson, and serialization-jackson features.

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/kotlin/example/micronaut/Fruit.kt
package example.micronaut

import io.micronaut.core.annotation.Creator
import io.micronaut.serde.annotation.Serdeable
import org.bson.codecs.pojo.annotations.BsonCreator
import org.bson.codecs.pojo.annotations.BsonProperty
import jakarta.validation.constraints.NotBlank

@Serdeable (1)
data class Fruit @Creator @BsonCreator constructor( (4)
    @field:BsonProperty("name") @param:BsonProperty("name") @field:NotBlank val name: String,  (2) (3)
    @field:BsonProperty("description") @param:BsonProperty("description") var description: String?) { (3)

    constructor(name: String) : this(name, null)
}
1 Declare the @Serdeable annotation at the type level in your source code to allow the type to be serialized or deserialized.
2 Use jakarta.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/kotlin/example/micronaut/FruitRepository.kt
package example.micronaut

import jakarta.validation.Valid

interface FruitRepository {

    fun list(): List<Fruit>

    fun save(@Valid fruit: Fruit) (1)
}
1 Add @Valid to any method parameter which requires validation.

4.3. Controller

Create FruitController:

src/main/kotlin/example/micronaut/FruitController.kt
package example.micronaut

import io.micronaut.http.HttpStatus.CREATED
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 jakarta.validation.Valid

@Controller("/fruits") (1)
@ExecuteOn(TaskExecutors.BLOCKING) (2)
open class FruitController(private val fruitService: FruitRepository) { (3)

    @Get (4)
    fun list(): List<Fruit> = fruitService.list()

    @Post (5)
    @Status(CREATED) (6)
    open fun save(@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/kotlin/example/micronaut/MongoDbConfiguration.kt
package example.micronaut

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

@ConfigurationProperties("db") (1)
interface MongoDbConfiguration : Named {

    val collection: String
}
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/kotlin/example/micronaut/MongoDbFruitRepository.kt
package example.micronaut

import com.mongodb.client.MongoClient
import com.mongodb.client.MongoCollection
import jakarta.inject.Singleton
import jakarta.validation.Valid

@Singleton (1)
open class MongoDbFruitRepository(
    private val mongoConf: MongoDbConfiguration,  (2)
    private val mongoClient: MongoClient) : FruitRepository { (3)

    override fun save(@Valid fruit: Fruit) {
        collection.insertOne(fruit)
    }

    override fun list(): List<Fruit> = collection.find().into(ArrayList())

    private val collection: MongoCollection<Fruit>
        get() = mongoClient.getDatabase(mongoConf.name)
                .getCollection(mongoConf.collection, Fruit::class.java)
}
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:

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.

4.6. Test

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

src/test/kotlin/example/micronaut/FruitClient.kt
package example.micronaut

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

@Client("/fruits")
interface FruitClient {

    @Post
    fun save(@Valid fruit: Fruit): HttpStatus

    @Get
    fun findAll(): List<Fruit>
}

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

pom.xml
<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>junit-jupiter</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>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:

src/test/kotlin/example/micronaut/FruitControllerTest.kt
package example.micronaut

import io.micronaut.http.HttpStatus.CREATED
import io.micronaut.test.extensions.junit5.annotation.MicronautTest
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import org.junit.jupiter.api.TestInstance.Lifecycle

@MicronautTest
class FruitControllerTest {

    @Test
    fun fruitsEndpointInteractsWithMongo(fruitClient: FruitClient) {

        var fruits = fruitClient.findAll()
        assertTrue(fruits.isEmpty())

        var status = fruitClient.save(Fruit("banana"))
        assertEquals(CREATED, status)

        fruits = fruitClient.findAll()
        assertFalse(fruits.isEmpty())
        assertEquals("banana", fruits[0].name)
        assertNull(fruits[0].description)

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

        fruits = fruitClient.findAll()
        assertTrue(fruits.any { (_, description): Fruit -> "Keeps the doctor away" == description })
    }
}

5. Test Resources

When the application is started locally — either under test or by running the application — 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

6. Testing the Application

To run the tests:

./mvnw test

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

8. Generate a Micronaut Application Native Executable with GraalVM

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

Compiling native executables 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. GraalVM installation

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

Java 17
sdk install java 17.0.8-graal
Java 17
sdk use java 17.0.8-graal

For installation on Windows, or for 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 17
sdk install java 17.0.8-graalce
Java 17
sdk use java 17.0.8-graalce

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

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

9. Next steps

Explore more features with Micronaut Guides.

10. Next Steps

11. Help with the Micronaut Framework

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

12. License

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