Access a database with Micronaut Data JDBC

Learn how to access a database with Micronaut JDBC repositories.

Authors: Sergio del Amo, John Shingler

Micronaut Version: 4.6.3

1. Getting Started

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

The application exposes some REST endpoints and stores data in a MySQL database using Micronaut Data JDBC.

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

  • Docker installed to run MySQL and to run tests using Testcontainers.

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=data-jdbc,flyway,jdbc-hikari,mysql,serialization-jackson,validation,graalvm \
    --build=maven \
    --lang=kotlin \
    --test=junit
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-jdbc, flyway, jdbc-hikari, mysql, serialization-jackson, validation, and graalvm 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. Data Source configuration

Define the datasource in src/main/resources/application.properties.

src/main/resources/application.properties
datasources.default.dialect=MYSQL
datasources.default.driver-class-name=com.mysql.cj.jdbc.Driver
This way of defining the datasource properties enables us to externalize the configuration, for example for production environment, and also provide a default value for development. If the environment variables are not defined, the Micronaut framework will use the default values.

4.2. 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:

pom.xml
<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.

src/main/resources/application.properties
(1)
flyway.datasources.default.enabled=true
1 Enable Flyway for the default datasource.
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:

src/main/resources/db/migration/V1__schema.sql
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.

4.3. Domain

Create the domain entities:

src/main/kotlin/example/micronaut/domain/Genre.kt
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

@Serdeable
@MappedEntity
data class Genre(
    @field:Id
    @field:GeneratedValue(GeneratedValue.Type.AUTO)
    var id: Long? = null,
    var name: String
)
You could use a subset of supported JPA annotations instead by including the following compileOnly scoped dependency: jakarta.persistence:jakarta.persistence-api.

4.4. Repository Access

Next, create a repository interface to define the operations to access the database. Micronaut Data will implement the interface at compilation time:

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

import example.micronaut.domain.Genre
import io.micronaut.data.annotation.Id
import io.micronaut.data.exceptions.DataAccessException
import io.micronaut.data.jdbc.annotation.JdbcRepository
import io.micronaut.data.model.query.builder.sql.Dialect
import io.micronaut.data.repository.PageableRepository
import jakarta.transaction.Transactional
import jakarta.validation.constraints.NotBlank

@JdbcRepository(dialect = Dialect.MYSQL) (1)
abstract class GenreRepository : PageableRepository<Genre, Long> { (2)

    abstract fun save(@NotBlank name: String) : Genre

    @Transactional
    open fun saveWithException(@NotBlank name: String): Genre {
        save(name)
        throw DataAccessException("test exception")
    }

    abstract fun update(@Id id: Long, @NotBlank name: String) : Long
}
1 @JdbcRepository with a specific dialect.
2 Genre, the entity to treat as the root entity for the purposes of querying, is established either from the method signature or from the generic type parameter specified to the GenericRepository interface.

The repository extends from PageableRepository. It inherits the hierarchy PageableRepositoryCrudRepositoryGenericRepository.

Repository Description

PageableRepository

A repository that supports pagination. It provides findAll(Pageable) and findAll(Sort).

CrudRepository

A repository interface for performing CRUD (Create, Read, Update, Delete). It provides methods such as findAll(), save(Genre), deleteById(Long), and findById(Long).

GenericRepository

A root interface that features no methods but defines the entity type and ID type as generic arguments.

4.5. 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:

pom.xml
<!-- Add the following to your annotationProcessorPaths element -->
<annotationProcessorPath>
    <groupId>io.micronaut.validation</groupId>
    <artifactId>micronaut-validation-processor</artifactId>
</annotationProcessorPath>
<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:

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

import io.micronaut.serde.annotation.Serdeable
import jakarta.validation.constraints.NotBlank

@Serdeable (1)
data class GenreUpdateCommand(
    val id: Long,
    @field:NotBlank val name: String
)
1 Declare the @Serdeable annotation at the type level in your source code to allow the type to be serialized or deserialized.

Create GenreController, a controller that exposes a resource with the common CRUD operations:

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

import example.micronaut.domain.Genre
import io.micronaut.data.exceptions.DataAccessException
import io.micronaut.data.model.Pageable
import io.micronaut.http.HttpHeaders
import io.micronaut.http.HttpResponse
import io.micronaut.http.HttpStatus
import io.micronaut.http.annotation.Body
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Delete
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.Post
import io.micronaut.http.annotation.Put
import io.micronaut.http.annotation.Status
import io.micronaut.scheduling.TaskExecutors
import io.micronaut.scheduling.annotation.ExecuteOn
import java.net.URI
import java.util.Optional
import jakarta.validation.Valid
import jakarta.validation.constraints.NotBlank

@ExecuteOn(TaskExecutors.BLOCKING) (1)
@Controller("/genres") (2)
open class GenreController(private val genreRepository: GenreRepository) { (3)


    @Get("/{id}") (4)
    fun show(id:Long): Optional<Genre> =
        genreRepository.findById(id) (5)

    @Put (6)
    open fun update(@Body @Valid command: GenreUpdateCommand): HttpResponse<Genre> { (7)
        val id = genreRepository.update(command.id, command.name)

        return HttpResponse
            .noContent<Genre>()
            .header(HttpHeaders.LOCATION, id.location.path) (8)
    }

    @Get("/list") (9)
    open fun list(@Valid pageable: Pageable): List<Genre> = (10)
        genreRepository.findAll(pageable).content


    @Post (11)
    open fun save(@Body("name") @NotBlank name: String) : HttpResponse<Genre> {
        val genre = genreRepository.save(name)

        return HttpResponse
            .created(genre)
            .headers { headers -> headers.location(genre.location) }
    }

    @Post("/ex") (12)
    open fun saveExceptions(@Body @NotBlank name: String): HttpResponse<Genre> {
        return try {
            val genre = genreRepository.saveWithException(name)

            HttpResponse
                .created(genre)
                .headers { headers -> headers.location(genre.location) }
        } catch (ex: DataAccessException) {
            HttpResponse.noContent()
        }
    }

    @Delete("/{id}") (13)
    @Status(HttpStatus.NO_CONTENT)
    fun delete(id: Long) = genreRepository.deleteById(id)

    private val Long?.location : URI
        get() = URI.create("/genres/$this")

    private val Genre.location : URI
        get() = id.location
}
1 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.
2 The class is defined as a controller with the @Controller annotation mapped to the path /genres.
3 Use constructor injection to inject a bean of type GenreRepository.
4 Maps a GET request to /genres/{id}, which attempts to show a genre. This illustrates the use of a URL path variable.
5 Returning an empty optional when the genre doesn’t exist makes the Micronaut framework respond with 404 (not found).
6 Maps a PUT request to /genres, which attempts to update a genre.
7 Adds @Valid to any method parameter that requires validation. Use a POJO supplied as a JSON payload in the request to populate command.
8 It is easy to add custom headers to the response.
9 Maps a GET request to /genres/list, which returns a list of genres. This mapping illustrates URL parameters being mapped to a single POJO.
10 You can bind Pageable as a controller method argument. Check the examples in the following test section and read the Pageable configuration options. For example, you can configure the default page size with the configuration property micronaut.data.pageable.default-page-size.
11 Maps a POST request to /genres, which attempts to save a genre.
12 Maps a POST request to /ex, which generates an exception.
13 Maps a DELETE request to /genres/{id}, which attempts to remove a genre. This illustrates the use of a URL path variable.

4.6. Writing Tests

Create a test to verify the CRUD operations:

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

import example.micronaut.domain.Genre
import io.micronaut.core.type.Argument
import io.micronaut.http.HttpHeaders
import io.micronaut.http.HttpRequest
import io.micronaut.http.HttpStatus
import io.micronaut.http.client.HttpClient
import io.micronaut.http.client.annotation.Client
import io.micronaut.http.client.exceptions.HttpClientResponseException
import io.micronaut.test.extensions.junit5.annotation.MicronautTest
import jakarta.inject.Inject
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows

@MicronautTest (1)
class GenreControllerTest(@Client("/") val client: HttpClient) { (2)

    @Test
    fun testFindNonExistingGenreReturn404() {
        val thrown = assertThrows<HttpClientResponseException>{
            client.toBlocking().exchange<Any>("/genres/99")
        }

        assertNotNull(thrown.response)
        assertEquals(HttpStatus.NOT_FOUND, thrown.status)
    }

    @Test
    fun testGenreCrudOperations() {

        var request = HttpRequest.POST("/genres", mapOf("name" to "DevOps")) (3)
        var response = client.toBlocking().exchange(request, Genre::class.java)

        assertEquals(HttpStatus.CREATED, response.status)
        assertEquals("/genres/1", response.header(HttpHeaders.LOCATION))

        request = HttpRequest.POST("/genres", mapOf("name" to "Microservices")) (3)
        response = client.toBlocking().exchange(request, Genre::class.java)

        assertEquals(HttpStatus.CREATED, response.status)
        assertEquals("/genres/2", response.header(HttpHeaders.LOCATION))

        var genre = client.toBlocking().retrieve("/genres/2", Genre::class.java) (4)

        assertEquals("Microservices", genre.name)

        var cmdRequest = HttpRequest.PUT("/genres", GenreUpdateCommand(2, "Micro-services"))
        response = client.toBlocking().exchange(cmdRequest) (5)

        assertEquals(HttpStatus.NO_CONTENT, response.status())

        genre = client.toBlocking().retrieve("/genres/2", Genre::class.java)

        assertEquals("Micro-services", genre.name)

        request = HttpRequest.GET("/genres/list")
        var genres = client.toBlocking().retrieve(request, Argument.listOf(Genre::class.java))

        assertEquals(2, genres.size)

        request = HttpRequest.POST("/genres/ex", mapOf("name" to "Microservices"))
        response = client.toBlocking().exchange(request)

        assertEquals(HttpStatus.NO_CONTENT, response.status)

        request = HttpRequest.GET("/genres/list")
        genres = client.toBlocking().retrieve(request, Argument.listOf(Genre::class.java))

        assertEquals(2, genres.size)

        request = HttpRequest.GET("/genres/list?size=1")
        genres= client.toBlocking().retrieve(request, Argument.listOf(Genre::class.java))

        assertEquals(1, genres.size)
        assertEquals("DevOps", genres[0].name)

        request = HttpRequest.GET("/genres/list?size=1&sort=name,desc")
        genres= client.toBlocking().retrieve(request, Argument.listOf(Genre::class.java))

        assertEquals(1, genres.size)
        assertEquals("Micro-services", genres[0].name)

        request = HttpRequest.GET("/genres/list?size=1&page=2")
        genres= client.toBlocking().retrieve(request, Argument.listOf(Genre::class.java))

        assertEquals(0, genres.size)

        for (i in 1..2) {
            request = HttpRequest.DELETE("/genres/$i")
            response = client.toBlocking().exchange(request)

            assertEquals(HttpStatus.NO_CONTENT, response.status)
        }

        request = HttpRequest.GET("/genres/list")
        genres = client.toBlocking().retrieve(request, Argument.listOf(Genre::class.java))

        assertEquals(0, genres.size)

    }

}
1 Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context and the embedded server. More info.
2 Inject the HttpClient bean and point it to the embedded server.
3 Creating HTTP Requests is easy thanks to the Micronaut framework fluid API.
4 If you care just about the object in the response, use retrieve.
5 Sometimes, receiving just the object is not enough, and you need information about the response. In this case, instead of retrieve, use the exchange method.

5. Testing the Application

To run the tests:

./mvnw test

6. Running the Application

To run the application, use the ./mvnw mn:run command, which starts the application on port 8080.

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

8. Test Resources

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

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

Export several environment variables:

export DATASOURCES_DEFAULT_URL=jdbc:mysql://localhost:3306/db
export DATASOURCES_DEFAULT_USERNAME=sherlock
export DATASOURCES_DEFAULT_PASSWORD=elementary

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

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 datasources.default.* properties.

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

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

10.1. GraalVM Installation

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

Java 21
sdk install java 21.0.5-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 21
sdk install java 21.0.2-graalce

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

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 following:

pom.xml
<plugin>
    <groupId>org.graalvm.buildtools</groupId>
    <artifactId>native-maven-plugin</artifactId>
    <version>0.10.3</version>
    <configuration>
        <!-- <1> -->
        <imageName>mn-graalvm-application</imageName> (1)
        <buildArgs>
              <!-- <2> -->
          <buildArg>-Ob</buildArg>
        </buildArgs>
    </configuration>
</plugin>
1 The native executable name will now be mn-graalvm-application.
2 It is possible to pass extra build arguments to native-image. For example, -Ob enables the quick build mode.

Before running the native executable, start a MySQL database and define the JDBC URL, username and password via environment variables described in the section Connecting to a MySQL database.

You can execute the genres endpoints exposed by the native executable, for example:

curl localhost:8080/genres/list

11. Next Steps

Read more about Micronaut Data.

12. Help with the Micronaut Framework

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

13. 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…​).