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

1. Getting Started

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

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 1.8 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=java
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.data:micronaut-data-hibernate-reactive") (1)
implementation("io.vertx:vertx-mysql-client") (2)
1 A dependency on micronaut-data’s Reactive Hibernate support.
2 Adds a dependency to the Vert.x MySQL client.

4.3. 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:
          url: ${JDBC_URL:`jdbc:mysql://localhost:3306/db`}
          username: ${JDBC_USER:root}
          password: ${JDBC_PASSWORD:my-secret-pw}
    reactive: true
1 Configure the package that contains our entity classes.
2 Configure how Hibernate will manage the database.

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

4.4. Domain

Create the domain entities:

src/main/java/example/micronaut/domain/Genre.java
package example.micronaut.domain;

import javax.persistence.GenerationType;
import javax.validation.constraints.NotNull;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Genre {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    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 + '\'' +
                '}';
    }
}

4.5. 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/java/example/micronaut/GenreRepository.java
package example.micronaut;

import example.micronaut.domain.Genre;
import io.micronaut.core.annotation.NonNull;
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 javax.transaction.Transactional;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

@Repository (1)
public interface GenreRepository extends ReactorPageableRepository<Genre, Long> { (2)

    Mono<Genre> save(@NonNull @NotBlank String name);

    @Transactional
    default Mono<Genre> saveWithException(@NonNull @NotBlank String name) {
        return save(name)
                .handle((genre, sink) -> {
                    sink.error(new DataAccessException("test exception"));
                });
    }

    Mono<Long> update(@NonNull @NotNull @Id Long id, @NonNull @NotBlank String 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.6. 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 a class to encapsulate the Update operations:

src/main/java/example/micronaut/GenreUpdateCommand.java
package example.micronaut;

import io.micronaut.core.annotation.Introspected;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

@Introspected (1)
public class GenreUpdateCommand {

    @NotNull
    private final Long id;

    @NotBlank
    private final String name;

    public GenreUpdateCommand(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }
}
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.

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

src/main/java/example/micronaut/GenreController.java
package example.micronaut;

import example.micronaut.domain.Genre;
import io.micronaut.data.exceptions.DataAccessException;
import io.micronaut.data.model.Page;
import io.micronaut.data.model.Pageable;
import io.micronaut.http.HttpHeaders;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.MutableHttpResponse;
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 reactor.core.publisher.Mono;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.net.URI;
import java.util.List;

@Controller("/genres")  (1)
public class GenreController {

    protected final GenreRepository genreRepository;

    public GenreController(GenreRepository genreRepository) { (2)
        this.genreRepository = genreRepository;
    }

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

    @Put (5)
    public Mono<HttpResponse<Genre>> update(@Body @Valid GenreUpdateCommand command) { (6)
        return genreRepository.update(command.getId(), command.getName())
                .map(e -> HttpResponse
                        .<Genre>noContent()
                        .header(HttpHeaders.LOCATION, location(command.getId()).getPath())); (7)

    }

    @Get("/list") (8)
    public Mono<List<Genre>> list(@Valid Pageable pageable) { (9)
        return genreRepository.findAll(pageable)
                .map(Page::getContent);
    }

    @Post (10)
    public Mono<HttpResponse<Genre>> save(@Body("name") @NotBlank String name) {
        return genreRepository.save(name)
                .map(genre -> HttpResponse.created(genre)
                        .headers(headers -> headers.location(location(genre.getId()))));
    }

    @Post("/ex") (11)
    public Mono<MutableHttpResponse<Genre>> saveExceptions(@Body @NotBlank String name) {
        return genreRepository
                .saveWithException(name)
                .map(genre -> HttpResponse
                        .created(genre)
                        .headers(headers -> headers.location(location(genre.getId())))
                )
                .onErrorReturn(DataAccessException.class, HttpResponse.noContent());
    }

    @Delete("/{id}") (12)
    public Mono<HttpResponse<?>> delete(Long id) {
        return genreRepository.deleteById(id)
                .map(deleteId -> HttpResponse.noContent());
    }

    protected URI location(Long id) {
        return URI.create("/genres/" + id);
    }

    protected URI location(Genre genre) {
        return location(genre.getId());
    }
}
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.7. 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/java/example/micronaut/BaseMysqlTest.java
package example.micronaut;

import io.micronaut.core.annotation.NonNull;
import io.micronaut.core.util.CollectionUtils;
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;

import java.util.Collections;
import java.util.Map;

@MicronautTest (1)
@TestInstance(TestInstance.Lifecycle.PER_CLASS) (2)
public class BaseMysqlTest implements TestPropertyProvider { (3)

    static GenericContainer<?> mysqlContainer;

    @Inject
    @Client("/")
    HttpClient httpClient; (4)

    void startMySQL() {
        if (mysqlContainer == null) {
            mysqlContainer = new GenericContainer<>(DockerImageName.parse("mysql:8.0.29"))
                    .withExposedPorts(3306)
                    .withEnv("MYSQL_ROOT_PASSWORD", "my-secret-pw")
                    .withEnv("MYSQL_DATABASE", "db")
                    .waitingFor(Wait.forLogMessage(".*/usr/sbin/mysqld: ready for connections.*\\n", 2));
        }
        if (!mysqlContainer.isRunning()) {
            mysqlContainer.start();
        }
    }

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

    @Override
    @NonNull
    public Map<String, String> getProperties() { (5)
        return CollectionUtils.mapOf(
                "jpa.default.properties.hibernate.connection.url", getMySQLDbUri(),
                "datasources.migration.url", getMySQLDbUri(),
                "datasources.migration.driverClassName", "com.mysql.cj.jdbc.Driver"
        );
    }

    @AfterAll
    public static void 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.

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.url: jdbc:tc:mysql:8:///db

Create a test to verify the CRUD operations:

src/test/java/example/micronaut/GenreControllerTest.java
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.exceptions.HttpClientResponseException;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;

public class GenreControllerTest extends BaseMysqlTest { (1)
    @Test
    public void testFindNonExistingGenreReturns404() {
        HttpClientResponseException thrown = assertThrows(HttpClientResponseException.class, () -> {
            httpClient.toBlocking().exchange(HttpRequest.GET("/genres/99"));
        });

        assertNotNull(thrown.getResponse());
        assertEquals(HttpStatus.NOT_FOUND, thrown.getStatus());
    }

    @Test
    public void testGenreCrudOperations() {

        List<Long> genreIds = new ArrayList<>();

        HttpRequest<?> request = HttpRequest.POST("/genres", Collections.singletonMap("name", "DevOps")); (2)
        HttpResponse<?> response = httpClient.toBlocking().exchange(request);
        genreIds.add(entityId(response));

        assertEquals(HttpStatus.CREATED, response.getStatus());

        request = HttpRequest.POST("/genres", Collections.singletonMap("name", "Microservices")); (3)
        response = httpClient.toBlocking().exchange(request);

        assertEquals(HttpStatus.CREATED, response.getStatus());

        Long id = entityId(response);
        genreIds.add(id);
        request = HttpRequest.GET("/genres/" + id);

        Genre genre = httpClient.toBlocking().retrieve(request, Genre.class); (4)

        assertEquals("Microservices", genre.getName());

        request = HttpRequest.PUT("/genres", new GenreUpdateCommand(id, "Micro-services"));
        response = httpClient.toBlocking().exchange(request);  (4)

        assertEquals(HttpStatus.NO_CONTENT, response.getStatus());

        request = HttpRequest.GET("/genres/" + id);
        genre = httpClient.toBlocking().retrieve(request, Genre.class);
        assertEquals("Micro-services", genre.getName());

        request = HttpRequest.GET("/genres/list");
        List<Genre> genres = httpClient.toBlocking().retrieve(request, Argument.of(List.class, Genre.class));

        assertEquals(2, genres.size());

        request = HttpRequest.POST("/genres/ex", Collections.singletonMap("name", "Microservices")); (2)
        response = httpClient.toBlocking().exchange(request);

        assertEquals(HttpStatus.NO_CONTENT, response.getStatus());

        request = HttpRequest.GET("/genres/list");
        genres = httpClient.toBlocking().retrieve(request, Argument.of(List.class, Genre.class));

        assertEquals(2, genres.size());

        request = HttpRequest.GET("/genres/list?size=1");
        genres = httpClient.toBlocking().retrieve(request, Argument.of(List.class, Genre.class));

        assertEquals(1, genres.size());
        assertEquals("DevOps", genres.get(0).getName());

        request = HttpRequest.GET("/genres/list?size=1&sort=name,desc");
        genres = httpClient.toBlocking().retrieve(request, Argument.of(List.class, Genre.class));

        assertEquals(1, genres.size());
        assertEquals("Micro-services", genres.get(0).getName());

        request = HttpRequest.GET("/genres/list?size=1&page=2");
        genres = httpClient.toBlocking().retrieve(request, Argument.of(List.class, Genre.class));

        assertEquals(0, genres.size());

        // cleanup:
        for (Long genreId : genreIds) {
            request = HttpRequest.DELETE("/genres/" + genreId);
            response = httpClient.toBlocking().exchange(request);
            assertEquals(HttpStatus.NO_CONTENT, response.getStatus());
        }
    }

    protected Long entityId(HttpResponse<?> response) {
        String path = "/genres/";
        String value = response.header(HttpHeaders.LOCATION);
        if (value == null) {
            return null;
        }
        int index = value.indexOf(path);
        if (index != -1) {
            return Long.valueOf(value.substring(index + path.length()));
        }
        return null;
    }
}
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.

6. Using MySQL

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

Start it with:

docker run \
    --rm \
    -d \
    -p 3306:3306 \
    -e MYSQL_ROOT_PASSWORD=my-secret-pw \
    -e MYSQL_DATABASE=db \
    mysql:latest

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

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

9. Help with the Micronaut Framework

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