Access a database with Micronaut Data R2DBC
Learn how to access a database with Micronaut R2DBC repositories.
On this guide
In this section
Getting Started
In this guide, we will create a Micronaut application written in Java.
The application exposes some REST endpoints and stores data in a MySQL database using Micronaut Data R2DBC.
What is R2DBC?
The Reactive Relational Database Connectivity (R2DBC) project brings reactive programming APIs to relational databases.
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 MySQL 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-r2dbc,flyway,mysql,test-resources,jdbc-hikari,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 data-r2dbc, flyway, mysql, test-resources, jdbc-hikari, 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. |
Data Source configuration
Define the R2DBC and the JDBC datasource in src/main/resources/application.properties (the latter is needed for Flyway migrations).
r2dbc.datasources.default.dialect=MYSQL
datasources.default.dialect=MYSQL|
Note
|
Only the dialect is defined. The remainder of the values (including the database URL etc.) will automatically be populated by the Test Resources integration, which uses Testcontainers. |
When deploying to production, the datasource connection properties and r2dbc connection properties can be specified externally (using environment variables for example).
Database Migration with Flyway
We need a way to create the database schema. For that, we use Micronaut integration with Flyway.
Flyway automates schema changes, significantly simplifying schema management tasks, such as migrating, rolling back, and reproducing in multiple environments.
Add the following snippet to include the necessary dependencies:
<dependency>
<groupId>io.micronaut.flyway</groupId>
<artifactId>micronaut-flyway</artifactId>
<scope>compile</scope>
</dependency>We will enable Flyway in the Micronaut configuration file and configure it to perform migrations on one of the defined data sources.
|
Note
|
Configuring multiple data sources is as simple as enabling Flyway for each one. You can also specify directories that will be used for migrating each data source. Review the Micronaut Flyway documentation for additional details. |
Flyway migration will be automatically triggered before your Micronaut application starts. Flyway will read migration commands in the resources/db/migration/ directory, execute them if necessary, and verify that the configured data source is consistent with them.
Create the following migration files with the database schema creation:
DROP TABLE IF EXISTS genre;
CREATE TABLE genre (
id BIGINT NOT NULL AUTO_INCREMENT UNIQUE PRIMARY KEY,
name VARCHAR(255) NOT NULL UNIQUE
);During application startup, Flyway will execute the SQL file and create the schema needed for the application.
Domain
Create the domain entity:
package example.micronaut.domain;
import io.micronaut.data.annotation.GeneratedValue;
import io.micronaut.data.annotation.Id;
import io.micronaut.data.annotation.MappedEntity;
import io.micronaut.serde.annotation.Serdeable;
import jakarta.validation.constraints.NotBlank;
@Serdeable
@MappedEntity
public class Genre {
@Id
@GeneratedValue(GeneratedValue.Type.AUTO)
private Long id;
@NotBlank
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Genre{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}|
Tip
|
You could use a subset of supported JPA annotations instead by including the following compileOnly scoped dependency: jakarta.persistence:jakarta.persistence-api.
|
Repository Access
Next, create a repository interface to define the operations to access the database. Micronaut Data will implement the interface at compilation time:
The repository extends from ReactorPageableRepository. It inherits the hierarchy ReactorPageableRepository → ReactorCrudRepository → ReactiveStreamsCrudRepository → GenericRepository.
| Repository | Description |
|---|---|
|
A repository that supports pagination. It provides |
|
A repository interface for performing CRUD (Create, Read, Update, Delete). It provides methods such as |
|
A root interface that features no methods but defines the entity type and ID type as generic arguments. |
Controller
Micronaut validation is built on the standard framework – JSR 380, also known as Bean Validation 2.0. Micronaut Validation has built-in support for validation of beans that are annotated with jakarta.validation annotations.
To use Micronaut Validation, you need the following dependencies:
<!-- Add the following to your annotationProcessorPaths element -->
<path>
<groupId>io.micronaut.validation</groupId>
<artifactId>micronaut-validation-processor</artifactId>
</path>
<dependency>
<groupId>io.micronaut.validation</groupId>
<artifactId>micronaut-validation</artifactId>
<scope>compile</scope>
</dependency>Alternatively, you can use Micronaut Hibernate Validator, which uses Hibernate Validator; a reference implementation of the validation API.
Create a class to encapsulate the update operations:
Create GenreController, a controller that exposes a resource with the common CRUD operations:
Writing Tests
Create a test to verify the CRUD operations:
Testing the Application
To run the tests:
./mvnw testRunning the Application
To run the application, use the ./mvnw mn:run command, which starts the application on port 8080.
Testing Running API
Save one genre, and your genre table will now contain an entry.
curl -X "POST" "http://localhost:8080/genres" \
-H 'Content-Type: application/json; charset=utf-8' \
-d $'{ "name": "music" }'Test Resources
When the application is started locally, either under test or while running locally, resolution of the datasource URL is detected and the Test Resources service will start a local MySQL docker container, and inject the properties required to use this as the datasource.
For more information, see the JDBC section or R2DBC section of the Test Resources documentation.
Connecting to a MySQL database
Previously, we connected to a MySQL database, which Micronaut Test Resources started for us.
However, it is easy to connect to an already existing database. Let’s start a database and connect to it.
Execute the following command to run a MySQL container:
docker run -it --rm \
-p 3306:3306 \
-e MYSQL_DATABASE=db \
-e MYSQL_USER=sherlock \
-e MYSQL_PASSWORD=elementary \
-e MYSQL_ALLOW_EMPTY_PASSWORD=true \
mysql:8|
Tip
|
If you are using macOS on Apple Silicon – e.g. M1, M1 Pro, etc. – Docker might fail to pull an image for mysql:8. In that case substitute mysql:oracle.
|
Database Migrations tools, such Flyway need a configured JDBC datasource. Export several environment variables:
export DATASOURCES_DEFAULT_URL=jdbc:mysql://localhost:3306/db
export DATASOURCES_DEFAULT_USERNAME=sherlock
export DATASOURCES_DEFAULT_PASSWORD=elementaryMicronaut Framework populates the properties datasources.default.url, datasources.default.username and datasources.default.password with those environment variables' values. Learn more about JDBC Connection Pools.
For R2DBC, export serveral environment variables:
export R2DBC_DATASOURCES_DEFAULT_URL=jdbc:mysql://localhost:3306/db
export R2DBC_DATASOURCES_DEFAULT_USERNAME=sherlock
export R2DBC_DATASOURCES_DEFAULT_PASSWORD=elementaryMicronaut Framework populates the properties r2dbc.datasources.default.url, r2dbc.datasources.default.username and r2dbc.datasources.default.password with those environment variables' values.
You can run the application and test the API as it was described in the previous sections. However, when you run the application, Micronaut Test Resources does not start a MySQL container because you have provided values for r2dbc.datasources.default. and datasources.default. properties.
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
sdk install java 25.0.2-graalFor 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:
sdk install java 25.0.2-graalceNative Executable Generation
To generate a native executable using Maven, run:
./mvnw package -Dpackaging=native-imageThe 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:
You can execute the genres endpoints exposed by the native image, for example:
curl localhost:8080/genres/listNext Steps
Read more about:
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). |