Access a database with JPA and Hibernate Reactive

Learn how to use Hibernate Reactive with the Micronaut Framework.

Authors: Tim Yates, Roman Naglic

Micronaut Version: 3.7.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:

  • Some time on your hands

  • A decent text editor or IDE

  • JDK 11 or greater installed with JAVA_HOME configured appropriately

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=gradle --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.

The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.

4.1. Enable annotation Processing

If you use Java or Kotlin and IntelliJ IDEA, make sure to enable annotation processing.

annotationprocessorsintellij

4.2. Data Source configuration

Add the following dependencies:

build.gradle
implementation("io.micronaut.reactor:micronaut-reactor") (1)
implementation("io.micronaut.sql:micronaut-hibernate-reactive") (2)
implementation("io.vertx:vertx-mysql-client") (3)
implementation("org.testcontainers:testcontainers") (4)
1 Add a dependency to the Micronaut Framework Project Reactor support
2 Configures Hibernate Reactive/JPA beans.
3 Adds a dependency to the Vert.x MySQL client.
4 Adds a dependency to the Testcontainers library which will be uses for testing the application.

4.3. JPA configuration

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

src/main/resources/application.yml
jpa:
  default:
    reactive: true
    properties:
      hibernate:
        hbm2ddl:
          auto: create-drop
        show_sql: true

4.4. Domain

Create the domain entities:

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

import com.fasterxml.jackson.annotation.JsonIgnore
import javax.persistence.*

@Entity
@Table(name = "genre")
class Genre(@Id
            @GeneratedValue(strategy = GenerationType.AUTO)
            @Column(name = "id", nullable = false, updatable = false)
            val id: Long?,

            @Column(name = "name", nullable = false)
            var name: String
) {

    @JsonIgnore
    @OneToMany(mappedBy = "genre")
    var books: MutableSet<Book> = mutableSetOf()

}

The previous domain has a OneToMany relationship with the domain Book.

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

import javax.persistence.*

@Entity
@Table(name = "book")
class Book(@Id
           @GeneratedValue(strategy = GenerationType.AUTO)
           var id: Long,

           @Column(name = "name", nullable = false)
           var name: String,

           @Column(name = "isbn", nullable = false)
           var isbn: String
) {


    @ManyToOne
    var genre: Genre? = null

}

4.5. Application Configuration

Create an interface to encapsulate the application configuration settings:

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

interface ApplicationConfiguration {
    val max: Int
}

Like Spring Boot and Grails, in Micronaut applications you can create typesafe configuration by creating classes that are annotated with @ConfigurationProperties.

Create a ApplicationConfigurationProperties class:

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

import io.micronaut.context.annotation.ConfigurationProperties

@ConfigurationProperties("application") (1)
class ApplicationConfigurationProperties : ApplicationConfiguration {
    private val DEFAULT_MAX = 10
    override var max = DEFAULT_MAX
}
1 The @ConfigurationProperties annotation takes the configuration prefix.

You can override max if you add to your src/main/resources/application.yml:

src/main/resources/application.yml
application:
  max: 50

4.6. Repository Access

Next, create a repository interface to define the operations to access the database:

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

import example.micronaut.domain.Genre
import org.reactivestreams.Publisher
import javax.validation.constraints.NotBlank

interface GenreRepository {
    fun findById(id: Long): Publisher<Genre?>
    fun save(name: String): Publisher<Genre>
    fun saveWithException(@NotBlank name: String): Publisher<Genre?>
    fun deleteById(id: Long)
    fun findAll(args: SortingAndOrderArguments): Publisher<Genre?>
    fun update(id: Long, @NotBlank name: String?): Publisher<Int?>
}

And the implementation:

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

import example.micronaut.domain.Genre
import jakarta.inject.Singleton
import org.hibernate.SessionFactory
import org.hibernate.reactive.stage.Stage
import org.reactivestreams.Publisher
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import javax.persistence.PersistenceException


@Singleton (1)
class GenreRepositoryImpl(
    val applicationConfiguration: ApplicationConfiguration, (2)
    sessionFactory: SessionFactory, (3)
) : GenreRepository {
    private val sessionFactory: Stage.SessionFactory
    private val VALID_PROPERTY_NAMES = arrayOf("id", "name")

    init {
        this.sessionFactory = sessionFactory.unwrap(Stage.SessionFactory::class.java)
    }

    override fun findById(id: Long): Publisher<Genre?> {
        return Mono.fromCompletionStage(sessionFactory.withTransaction { session -> (4)
            session.find(Genre::class.java, id)
        })
    }

    override fun save(name: String): Publisher<Genre> {
        return Mono.fromCompletionStage(sessionFactory.withTransaction { session ->
            val entity = Genre(id = null, name = name)
            session.persist(entity)
                .thenApply { entity }
        })
    }

    override fun update(id: Long, name: String?): Publisher<Int?> {
        return Mono.fromCompletionStage(sessionFactory.withTransaction { session ->
            session.createQuery<Long>("UPDATE Genre g SET name = :name where id = :id")
                .setParameter("name", name)
                .setParameter("id", id)
                .executeUpdate()
        })
    }

    override fun findAll(args: SortingAndOrderArguments): Publisher<Genre?> {
        val qlString: String = createQuery(args)
        return Mono.fromCompletionStage(sessionFactory.withSession { session ->
            val query = session.createQuery(
                qlString,
                Genre::class.java
            )
            query.maxResults = args.max ?: applicationConfiguration.max
            args.offset?.let { query.setFirstResult(it) }
            query.resultList
        })
            .flatMapMany { Flux.fromIterable(it) }
    }

    private fun createQuery(args: SortingAndOrderArguments): String {
        var qlString = "SELECT g FROM Genre as g"
        if (null != args.order && null != args.sort && VALID_PROPERTY_NAMES.contains(args.sort)) {
            qlString += " ORDER BY g." + args.sort + ' ' + args.order!!.lowercase()
        }
        return qlString
    }

    override fun deleteById(id: Long) {
        sessionFactory.withTransaction { session ->
            session.find(Genre::class.java, id).thenApply { entity ->
                session.remove(entity)
            }
        }
    }

    override fun saveWithException(name: String): Publisher<Genre?> {
        return Mono.fromCompletionStage(sessionFactory.withTransaction { session ->
            val entity = Genre(id = null, name = name)
            session.persist(entity)
                .thenApply<Genre> { throw PersistenceException() }
        })
    }
}
1 Use jakarta.inject.Singleton to designate a class as a singleton.
2 Inject the ApplicationConfiguration.
3 Inject the Hibernate SessionFactory.
4 Grab a transactional session from the SessionFactory to run our query.

4.7. Controller

Micronaut validation is built on the standard framework – JSR 380, also known as Bean Validation 2.0.

Hibernate Validator is a reference implementation of the validation API. Micronaut has built-in support for validation of beans that are annotated with javax.validation annotations.

The necessary dependencies are included by default when creating a new application, so you don’t need to add anything else.

Create two classes to encapsulate Save and Update operations:

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

import io.micronaut.core.annotation.Introspected
import javax.validation.constraints.NotBlank

@Introspected (1)
class GenreSaveCommand(@field:NotBlank var name: String)
1 Annotate the class with @Introspected to generate BeanIntrospection metadata at compilation time. This information can be used, for example, to render the POJO as JSON using Jackson without using reflection.
src/main/kotlin/example/micronaut/GenreUpdateCommand.kt
package example.micronaut

import io.micronaut.core.annotation.Introspected
import javax.validation.constraints.NotBlank

@Introspected
class GenreUpdateCommand(var id: Long, @field:NotBlank var name: String?)

Create a POJO to encapsulate Sorting and Pagination:

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

import io.micronaut.core.annotation.Introspected
import javax.validation.constraints.Pattern
import javax.validation.constraints.Positive
import javax.validation.constraints.PositiveOrZero

@Introspected
class SortingAndOrderArguments {
    @field:PositiveOrZero var offset:  Int? = null (1)
    @field:Positive var max: Int? = null (1)
    @field:Pattern(regexp = "id|name") var sort: String? = null (1)
    @field:Pattern(regexp = "asc|ASC|desc|DESC") var order: String? = null (1)
}
1 Use javax.validation.constraints Constraints to ensure the incoming data matches your expectations.

Create GenreController, a controller which 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.core.async.annotation.SingleResult
import io.micronaut.http.*
import io.micronaut.http.annotation.*
import org.reactivestreams.Publisher
import reactor.core.publisher.Mono
import java.net.URI
import javax.persistence.PersistenceException
import javax.validation.Valid

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

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

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

    private fun location(id: Long): URI {
        return URI.create("/genres/$id")
    }

    @Get(value = "/list{?args*}") (8)
    open fun list(@Valid args: SortingAndOrderArguments): Publisher<Genre?> {
        return genreRepository.findAll(args)
    }

    @Post (9)
    @SingleResult
    open fun save(@Valid @Body cmd: GenreSaveCommand): Publisher<HttpResponse<Genre>>? {
        return Mono.from(genreRepository.save(cmd.name))
            .map { genre ->
                HttpResponse
                    .created(genre)
                    .headers { headers ->
                        headers.location(location(genre.id!!))
                    }
            }
    }

    @Post("/ex") (10)
    @SingleResult
    open fun saveExceptions(@Valid @Body cmd: GenreSaveCommand): Publisher<MutableHttpResponse<Genre?>> {
        return Mono.from(genreRepository.saveWithException(cmd.name))
            .map { genre: Genre? ->
                HttpResponse
                    .created(genre)
                    .headers { headers: MutableHttpHeaders ->
                        headers.location(
                            location(
                                genre!!.id!!
                            )
                        )
                    }
            }
            .onErrorReturn(PersistenceException::class.java, HttpResponse.noContent())
    }

    @Delete("/{id}") (11)
    @Status(HttpStatus.NO_CONTENT) (12)
    fun delete(id: Long): HttpResponse<*> {
        genreRepository.deleteById(id)
        return HttpResponse.noContent<Any>()
    }
}
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 The @Get annotation maps the show method to an HTTP GET request on /{id}.
4 Returning an empty Publisher 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 Add @Valid to any method parameter which requires validation.
7 Add custom headers to the response.
8 Maps a GET request to /genres which returns a list of genres.
9 Maps a POST request to /genres which attempts to save a genre.
10 Maps a POST request to /ex which generates an exception.
11 The @Delete annotation maps the delete method to an HTTP Delete request on /genres/{id}.
12 You can return void in your controller’s method and specify the HTTP status code via the @Status annotation.

4.8. Writing Tests

To allow us to run a MySQL instance in a Docker container for testing, create a base class that sets this up.

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

import io.micronaut.http.client.HttpClient
import io.micronaut.http.client.annotation.Client
import io.micronaut.runtime.EmbeddedApplication
import io.micronaut.test.extensions.junit5.annotation.MicronautTest
import io.micronaut.test.support.TestPropertyProvider
import jakarta.inject.Inject
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.TestInstance
import org.testcontainers.containers.GenericContainer
import org.testcontainers.containers.wait.strategy.Wait
import org.testcontainers.utility.DockerImageName

@MicronautTest (1)
@TestInstance(TestInstance.Lifecycle.PER_CLASS) (2)
open class BaseMysqlTest: TestPropertyProvider { (3)
    var mysqlContainer: GenericContainer<*>? = null

    @Inject
    open var application: EmbeddedApplication<*>? = null

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

    override fun getProperties(): MutableMap<String, String> { (5)
        return mutableMapOf(Pair("jpa.default.properties.hibernate.connection.url", getMySQLDbUri()) )
    }

    open fun startMySQL() {
        if (mysqlContainer == null) {
            mysqlContainer = GenericContainer(DockerImageName.parse("mysql:oracle"))
                .withExposedPorts(3306)
                .withEnv("MYSQL_ROOT_PASSWORD", "pass")
                .waitingFor(Wait.forLogMessage(".*/usr/sbin/mysqld: ready for connections.*\\n", 2))
        }
        if (!mysqlContainer!!.isRunning) {
            mysqlContainer!!.start()
        }
    }

    open fun getMySQLDbUri(): String {
        if (mysqlContainer == null || !mysqlContainer!!.isRunning) {
            startMySQL()
        }
        return "jdbc:mysql://localhost:" + mysqlContainer!!.getMappedPort(3306) + "/mysql"
    }

    @AfterAll
    open fun stop() {
        mysqlContainer!!.close()
    }
}
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 When you need dynamic properties definition, implement the TestPropertyProvider interface. Override the method .getProperties() and return the properties you want to expose to the application.
4 Inject the HttpClient bean and point it to the embedded server.
5 Configure the application properties to that of the MySQL instance.

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.BlockingHttpClient
import io.micronaut.http.client.exceptions.HttpClientResponseException
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test

class GenreControllerTest: BaseMysqlTest() { (1)
    var blockingClient: BlockingHttpClient? = null

    @BeforeEach
    fun setup() {
        blockingClient = httpClient.toBlocking()
    }

    @Test
    fun supplyAnInvalidOrderTriggersValidationFailure() {
        val thrown = Assertions.assertThrows(HttpClientResponseException::class.java) {
            blockingClient!!.exchange<Any, Any>(HttpRequest.GET("/genres/list?order=foo"))
        }
        Assertions.assertNotNull(thrown.response)
        Assertions.assertEquals(HttpStatus.BAD_REQUEST, thrown.status)
    }

    @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", GenreSaveCommand("DevOps")) (2)
        var response: HttpResponse<Genre> = blockingClient!!.exchange(request)
        genreIds.add(entityId(response))
        Assertions.assertEquals(HttpStatus.CREATED, response.status)

        request = HttpRequest.POST("/genres", GenreSaveCommand("Microservices")) (2)
        response = blockingClient!!.exchange(request)
        Assertions.assertEquals(HttpStatus.CREATED, response.status)

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

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

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

        request = HttpRequest.GET<Any>("/genres/list")
        var genres = blockingClient!!.retrieve(
            request, Argument.listOf(Genre::class.java)
        )
        Assertions.assertEquals(2, genres.size)

        request = HttpRequest.POST("/genres/ex", GenreSaveCommand("Microservices")) (2)
        response = blockingClient!!.exchange(request)
        Assertions.assertEquals(HttpStatus.NO_CONTENT, response.status)

        request = HttpRequest.GET<Any>("/genres/list")
        genres = blockingClient!!.retrieve(
            request, Argument.listOf(Genre::class.java)
        )
        Assertions.assertEquals(2, genres.size)

        request = HttpRequest.GET<Any>("/genres/list?max=1")
        genres = blockingClient!!.retrieve(
            request, Argument.listOf(Genre::class.java)
        )
        Assertions.assertEquals(1, genres.size)
        Assertions.assertEquals("DevOps", genres[0].name)

        request = HttpRequest.GET<Any>("/genres/list?max=1&order=desc&sort=name")
        genres = blockingClient!!.retrieve(
            request, Argument.listOf(Genre::class.java)
        )
        Assertions.assertEquals(1, genres.size)
        Assertions.assertEquals("Micro-services", genres[0].name)

        request = HttpRequest.GET<Any>("/genres/list?max=1&offset=10")
        genres = blockingClient!!.retrieve(
            request, Argument.listOf(Genre::class.java)
        )
        Assertions.assertEquals(0, genres.size)

        // cleanup:
        for (genreId in genreIds) {
            request = HttpRequest.DELETE<Any>("/genres/$genreId")
            response = blockingClient!!.exchange(request)
            Assertions.assertEquals(HttpStatus.NO_CONTENT, response.status)
        }
    }

    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 Extend the BaseMysqlTest class.
2 Creating HTTP Requests is easy thanks to the Micronaut framework fluid API.
3 If you care just about the object in the response use retrieve.
4 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:

./gradlew test

Then open build/reports/tests/test/index.html in a browser to see the results.

To define the username and password for our Testcontainers MySQL instance, create a application-test.yml file in src/test/resources:

src/test/resources/application-test.yml
jpa:
  default:
    properties:
      hibernate:
        connection:
          username: root
          password: pass

6. Using MySQL

To run the application, we will use a real database instance running in Docker.

Start it with:

docker run \
    -p 3306:3306 \
    -e MYSQL_ROOT_PASSWORD=pass \
    mysql:oracle

For configuration with local development, create an application-dev.yml file in the src/main/resources directory:

src/main/resources/application-dev.yml
jpa:
  default:
    properties:
      hibernate:
        connection:
          url: jdbc:mysql://localhost:3306/mysql # Use JDBC style url
          username: root
          password: pass

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

export JPA_DEFAULT_PROPERTIES_HIBERNATE_CONNECTION_URL=jdbc:mysql://localhost:5432/micronaut
export JPA_DEFAULT_PROPERTIES_HIBERNATE_CONNECTION_USERNAME=dbuser
export JPA_DEFAULT_PROPERTIES_HIBERNATE_CONNECTION_PASSWORD=theSecretPassword

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

7. Running the Application

To run the application, use the ./gradlew 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" }'

8. Next steps

Read more about Configurations for Data Access section in the Micronaut documentation.

9. Help with the Micronaut Framework

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