Access a database with Micronaut Data and Hibernate Reactive

Learn how to use Micronaut Data and Hibernate Reactive

Authors: Sergio del Amo, Tim Yates, Roman Naglic

Micronaut Version: 4.4.0

1. Getting Started

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

In this guide, we will write a Micronaut application that exposes some REST endpoints and stores data in a database using JPA and Hibernate.

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 --build=maven --lang=kotlin
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.

4.1. Data Source configuration

Add the following dependencies:

pom.xml
<dependency> (1)
    <groupId>io.micronaut.data</groupId>
    <artifactId>micronaut-data-hibernate-reactive</artifactId>
    <scope>compile</scope>
</dependency>
<dependency> (2)
    <groupId>io.vertx</groupId>
    <artifactId>vertx-mysql-client</artifactId>
    <scope>compile</scope>
</dependency>
1 A dependency on micronaut-data’s Reactive Hibernate support.
2 Adds a dependency to the Vert.x MySQL client.

4.2. JPA configuration

Add the next snippet to src/main/resources/application.yml to configure JPA:

src/main/resources/application.yml
jpa:
  default:
    entity-scan:
      packages:
        - 'example.micronaut.domain' (1)
    properties:
      hibernate:
        show-sql: true
        hbm2ddl:
          auto: update (2)
        connection:
          db-type: mysql (3)
    reactive: true
1 Configure the package that contains our entity classes.
2 Configure how Hibernate will manage the database.
3 Configure the database type for Test Resources

With update for the hbm2ddl option, Hibernate creates the database schema.

4.3. Domain

Create the domain entities:

src/main/kotlin/example/micronaut/domain/Genre.kt
package example.micronaut.domain

import io.micronaut.serde.annotation.Serdeable
import jakarta.persistence.Entity
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id
import jakarta.validation.constraints.NotBlank
import jakarta.validation.constraints.NotNull

@Serdeable
@Entity
class Genre(@Id
            @GeneratedValue(strategy = GenerationType.IDENTITY)
            val id: Long?,

            @NotBlank
            var name: String
)

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.annotation.Repository
import io.micronaut.data.exceptions.DataAccessException
import io.micronaut.data.repository.reactive.ReactorPageableRepository
import reactor.core.publisher.Mono
import jakarta.transaction.Transactional
import jakarta.validation.constraints.NotBlank

@Repository (1)
abstract class GenreRepository: ReactorPageableRepository<Genre, Long> { (2)

    open fun save(@NotBlank name: String): Mono<Genre?> {
        return save(Genre(id = null, name = name))
    }

    @Transactional
    open fun saveWithException(@NotBlank name: String): Mono<Genre> {
        return save(name)
            .handle { _, sink ->
                sink.error(DataAccessException("test exception"))
            }
    }

    open fun update(@Id id: Long, @NotBlank name: String): Mono<Genre> {
        return update(Genre(id = id, name = name))
    }
}
1 Annotate with @Repository to allow compile time implementations to be added.
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 ReactorPageableRepository. It inherits the hierarchy ReactorPageableRepositoryReactorCrudRepositoryGenericRepository.

Repository Description

ReactorPageableRepository

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

ReactorCrudRepository

A repository interface for performing reactive 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)
class GenreUpdateCommand(var id: Long, @field:NotBlank var 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.MutableHttpHeaders
import io.micronaut.http.MutableHttpResponse
import io.micronaut.http.annotation.*
import io.micronaut.http.uri.UriBuilder
import reactor.core.publisher.Mono
import java.net.URI
import jakarta.validation.Valid
import jakarta.validation.constraints.NotBlank

@Controller("/genres")  (1)
open class GenreController(private val genreRepository: GenreRepository) { (2)

    @Get("/{id}") (3)
    fun show(id: Long): Mono<Genre?> {
        return genreRepository.findById(id) (4)
    }

    @Put (5)
    open fun update(@Valid @Body command: GenreUpdateCommand): Mono<HttpResponse<Genre>> { (6)
        return genreRepository.update(command.id, command.name)
            .map {
                HttpResponse
                    .noContent<Genre>()
                    .header(HttpHeaders.LOCATION, location(command.id).path)
            } (7)
    }

    @Get("/list") (8)
    open fun list(@Valid pageable: Pageable): Mono<List<Genre?>> { (9)
        return genreRepository.findAll(pageable)
            .map { obj -> obj.content }
    }

    @Post (10)
    open fun save(@NotBlank @Body("name") name: String): Mono<HttpResponse<Genre>> {
        return genreRepository.save(name)
            .map {
                HttpResponse.created(it!!)
                    .headers { headers: MutableHttpHeaders ->
                        headers.location(location(it.id!!))
                    }
            }
    }

    @Post("/ex") (11)
    open fun saveExceptions(@NotBlank @Body name: String): Mono<MutableHttpResponse<Genre?>> {
        return genreRepository
            .saveWithException(name)
            .map { genre ->
                HttpResponse
                    .created(genre)
                    .headers { headers ->
                        headers.location(location(genre?.id!!))
                    }
            }
            .onErrorReturn(DataAccessException::class.java, HttpResponse.noContent())
    }

    @Delete("/{id}") (12)
    open fun delete(id: Long): Mono<HttpResponse<*>>? {
        return genreRepository.deleteById(id)
            .map { HttpResponse.noContent<Any>() }
    }

    private fun location(id: Long): URI {
        return UriBuilder.of("/genres").path(id.toString()).build()
    }
}
1 The class is defined as a controller with the @Controller annotation mapped to the path /genres.
2 Use constructor injection to inject a bean of type GenreRepository.
3 Maps a GET request to /genres/{id}, which attempts to show a genre. This illustrates the use of a URL path variable.
4 Returning an empty optional when the genre doesn’t exist makes the Micronaut framework respond with 404 (not found).
5 Maps a PUT request to /genres, which attempts to update a genre.
6 Adds @Valid to any method parameter that requires validation. Use a POJO supplied as a JSON payload in the request to populate command.
7 It is easy to add custom headers to the response.
8 Maps a GET request to /genres/list, which returns a list of genres. This mapping illustrates URL parameters being mapped to a single POJO.
9 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.
10 Maps a POST request to /genres, which attempts to save a genre.
11 Maps a POST request to /ex, which generates an exception.
12 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.HttpResponse
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.awaitility.Awaitility.await
import org.hamcrest.Matchers.equalTo
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test

import org.junit.jupiter.api.TestInstance

@MicronautTest (1)
@TestInstance(TestInstance.Lifecycle.PER_CLASS) (2)
class GenreControllerTest { (3)

    @Inject
    @field:Client("/")
    lateinit var httpClient: HttpClient (3)

    @Test
    fun testFindNonExistingGenreReturns404() {
        val thrown = Assertions.assertThrows(HttpClientResponseException::class.java) {
            httpClient.toBlocking().exchange<Any, Any>(HttpRequest.GET("/genres/99"))
        }
        Assertions.assertNotNull(thrown.response)
        Assertions.assertEquals(HttpStatus.NOT_FOUND, thrown.status)
    }

    @Test
    fun testGenreCrudOperations() {
        val genreIds = mutableListOf<Long?>()

        var request: HttpRequest<*> = HttpRequest.POST("/genres", mapOf("name" to "DevOps")) (4)
        var response: HttpResponse<Genre> = httpClient.toBlocking().exchange(request)
        genreIds.add(entityId(response))
        Assertions.assertEquals(HttpStatus.CREATED, response.status)

        request = HttpRequest.POST("/genres", mapOf("name" to "Microservices")) (5)
        response = httpClient.toBlocking().exchange(request)
        Assertions.assertEquals(HttpStatus.CREATED, response.status)

        val id = entityId(response)
        genreIds.add(id)
        request = HttpRequest.GET<Any>("/genres/$id")
        var genre = httpClient.toBlocking().retrieve(request, Genre::class.java) (6)
        Assertions.assertEquals("Microservices", genre.name)

        request = HttpRequest.PUT("/genres", GenreUpdateCommand(id!!, "Micro-services"))
        response = httpClient.toBlocking().exchange(request) (6)
        Assertions.assertEquals(HttpStatus.NO_CONTENT, response.status)

        request = HttpRequest.GET<Any>("/genres/$id")
        genre = httpClient.toBlocking().retrieve(request, Genre::class.java)
        Assertions.assertEquals("Micro-services", genre.name)

        await().until(countEntities(), equalTo(2))

        request = HttpRequest.POST("/genres/ex", mapOf("name" to "Microservices")) (4)
        response = httpClient.toBlocking().exchange(request)
        Assertions.assertEquals(HttpStatus.NO_CONTENT, response.status)

        await().until(countEntities(), equalTo(2))

        request = HttpRequest.GET<Any>("/genres/list?size=1")
        var genres = httpClient.toBlocking().retrieve(request, Argument.listOf(Genre::class.java))
        Assertions.assertEquals(1, genres.size, "Expected 1 genre, got $genres")
        Assertions.assertEquals("DevOps", genres[0].name)

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

        Assertions.assertEquals(1, genres.size, "Expected 1 genre, got $genres")
        Assertions.assertEquals("Micro-services", genres[0].name)

        request = HttpRequest.GET<Any>("/genres/list?size=1&page=10")
        genres = httpClient.toBlocking().retrieve(request, Argument.listOf(Genre::class.java))
        Assertions.assertEquals(0, genres.size, "Expected 0 genres, got $genres")

        // cleanup:
        genreIds.forEach { genreId ->
            request = HttpRequest.DELETE<Any>("/genres/$genreId")
            response = httpClient.toBlocking().exchange(request)
            Assertions.assertEquals(HttpStatus.NO_CONTENT, response.status)
        }
    }

    private fun countEntities() = { ->
        httpClient
            .toBlocking()
            .retrieve(HttpRequest.GET<Any>("/genres/list"), Argument.listOf(Genre::class.java))
            .size
    }

    private fun entityId(response: HttpResponse<*>): Long? {
        val path = "/genres/"
        val value = response.header(HttpHeaders.LOCATION) ?: return null
        val id = value.substringAfter(path)
        if (id.isBlank()) return null
        return id.toLong()
    }
}
1 Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context and the embedded server. More info.
2 Classes that implement TestPropertyProvider must use this annotation to create a single class instance for all tests (not necessary in Spock tests).
3 Inject the HttpClient bean and point it to the embedded server.
4 Creating HTTP Requests is easy thanks to the Micronaut framework fluid API.
5 If you care just about the object in the response use retrieve.
6 Sometimes, receiving just the object is not enough and you need information about the response. In this case, instead of retrieve you should use the exchange method.

5. Testing the Application

To run the tests:

./mvnw test

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

7. Using MySQL

When you move to production, you will need to configure the properties injected by Test Resources to point at your real production database. This can be done via environment variables like so:

export JDBC_URL=jdbc:mysql://production-server:3306/micronaut
export JDBC_USER=dbuser
export JDBC_PASSWORD=theSecretPassword

Run the application. If you look at the output you can see that the application uses MySQL:

8. Running the Application

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

..
...
16:31:01.155 [main] INFO  org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
....

Connect to your MySQL database, and you will see both genre and book tables.

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

9. Next steps

10. Help with the Micronaut Framework

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

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