Micronaut MongoDB Synchronous
Learn how to use a blocking MongoClient with a Micronaut application
On this guide
In this section
Getting Started
In this guide, we will create a Micronaut application written in Groovy.
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
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=mongo-sync,serialization-bson,serialization-jackson \
--build=gradle \
--lang=groovy \
--test=spock|
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, and serialization-jackson 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:
Repository
Create a repository interface to encapsulate the CRUD actions for Fruit.
Controller
Create FruitController:
Configuration
Create a configuration object to encapsulate the MongoDB database name and collection name.
Define the values via configuration:
db.name=fruit
db.collection=fruitMongoDB repository
Implement FruitRepository by using a MongoDbClient.
By using the feature mongo-sync, the application includes the following dependency:
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.
Test
Add a Micronaut declarative HTTP Client to src/test to ease the testing of the application’s API.
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
@Client('/fruits')
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:
testImplementation("org.testcontainers:testcontainers-junit-jupiter")
testImplementation("org.testcontainers:testcontainers-mongodb")
testImplementation("org.testcontainers:testcontainers")Test Resources will provide us with a MongoDB instance for local testing and execution.
Create a test:
package example.micronaut
import io.micronaut.http.HttpStatus
import io.micronaut.test.extensions.spock.annotation.MicronautTest
import jakarta.inject.Inject
import spock.lang.Specification
import static io.micronaut.http.HttpStatus.CREATED
@MicronautTest
class FruitControllerSpec extends Specification {
@Inject
FruitClient fruitClient
void fruitsEndpointInteractsWithMongo() {
when:
List<Fruit> fruits = fruitClient.findAll()
then:
!fruits
when:
HttpStatus status = fruitClient.save(new Fruit('banana'))
then:
CREATED == status
when:
fruits = fruitClient.findAll()
then:
fruits
'banana' == fruits[0].name
null == fruits[0].description
when:
status = fruitClient.save(new Fruit('Apple', 'Keeps the doctor away'))
then:
CREATED == status
when:
fruits = fruitClient.findAll()
then:
fruits.find { it.description == 'Keeps the doctor away' }
}
}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"}]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.
Next Steps
Read more about the integration between the Micronaut framework 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). |