Java / Maven

Access a database with Micronaut Data and Hibernate Reactive

Learn how to use Micronaut Data and Hibernate Reactive.

Sergio del Amo, Tim Yates, Roman Naglic
On this guide
In this section

Getting Started

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

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

What you will need

To complete this guide, you will need the following:

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.

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

Data Source configuration

Add the following dependencies:

pom.xml

JPA configuration

Add the following snippet to src/main/resources/application.properties to configure JPA:

src/main/resources/application.properties

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

Domain

Create the domain entities:

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

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

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

Repository Access

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

java/src/main/java/example/micronaut/GenreRepository.java

The repository extends 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.

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

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

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

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

Writing Tests

Create a test to verify the CRUD operations:

java/src/test/java/example/micronaut/GenreControllerTest.java

Testing the Application

To run the tests:

./mvnw test

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.

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

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

Next Steps

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