Java / Maven

Micronaut Data and Java Records

Learn how to leverage Java records for immutable configuration, Micronaut Data Mapped Entities and Projection DTOs

Sergio del Amo
On this guide
In this section

Getting Started

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

You are going to use Record Classes in a Micronaut application.

Record classes, which are a special kind of class, help to model plain data aggregates with less ceremony than normal classes.

A record declaration specifies in a header a description of its contents; the appropriate accessors, constructor, equals, hashCode, and toString methods are created automatically. A record’s fields are final because the class is intended to serve as a simple "data carrier."

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.

Create an application using the Micronaut Command Line Interface or with Micronaut Launch.

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,liquibase,postgres,serialization-jackson,validation,graalvm \
    --build=maven \
    --lang=java \
    --test=junit
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.

If you use Micronaut Launch, select Micronaut Application as application type and add data-jdbc, liquibase, postgres, serialization-jackson, validation, and graalvm features.

Note
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.
mn create-app \
   example.micronaut.micronautguide \
   --features=data-jdbc,postgres,liquibase \
   --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.

Note
If you use Micronaut Launch, select "Micronaut Application" as application type and add postgres, data-jdbc, and liquibase as features.

Immutable Configuration with Java Records

java/src/main/java/example/micronaut/ValueAddedTaxConfiguration.java

Write a test:

java/src/test/java/example/micronaut/ValueAddedTaxConfigurationTest.java

Database Migration with Liquibase

We need a way to create the database schema. For that, we use Micronaut integration with Liquibase.

Add the following snippet to include the necessary dependencies:

pom.xml
<dependency>
    <groupId>io.micronaut.liquibase</groupId>
    <artifactId>micronaut-liquibase</artifactId>
    <scope>compile</scope>
</dependency>

Configure the database migrations directory for Liquibase in application.properties.

java/src/main/resources/application.properties
liquibase.enabled=true
liquibase.datasources.default.change-log=classpath:db/liquibase-changelog.xml

Create the following files with the database schema creation and a book:

java/src/main/resources/db/liquibase-changelog.xml
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
        xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
         http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
    <include file="changelog/01-create-books-schema.xml" relativeToChangelogFile="true"/>
    <include file="changelog/02-insert-book.xml" relativeToChangelogFile="true"/>
</databaseChangeLog>
java/src/main/resources/db/changelog/01-create-books-schema.xml
<?xml version="1.0" encoding="UTF-8"?>

<databaseChangeLog
        xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
         http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
    <changeSet id="01" author="sdelamo">
        <createTable tableName="book" remarks="A table to contain all books">
            <column name="isbn" type="varchar(255)">
                <constraints nullable="false" unique="true" primaryKey="true"/>
            </column>
            <column name="title" type="varchar(255)">
                <constraints nullable="false"/>
            </column>
            <column name="price" type="NUMERIC">
                <constraints nullable="false"/>
            </column>
            <column name="about" type="LONGVARCHAR">
                <constraints nullable="true"/>
            </column>
        </createTable>
    </changeSet>
</databaseChangeLog>
java/src/main/resources/db/changelog/02-insert-book.xml
<?xml version="1.0" encoding="UTF-8"?>

<databaseChangeLog
        xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
         http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
    <changeSet id="02" author="sdelamo">
        <insert tableName="book">
            <column name="isbn">0321601912</column>
            <column name="title">Continuous Delivery</column>
            <column name="price">39.99</column>
            <column name="about">Winner of the 2011 Jolt Excellence Award! Getting software released to users is often a painful, risky, and time-consuming process. This groundbreaking new book sets out the principles and technical practices that enable rapid, incremental delivery of high quality, valuable new functionality to users.</column>
        </insert>
    </changeSet>
</databaseChangeLog>

During application startup, Liquibase executes the SQL file, creates the schema needed for the application and inserts one book.

Mapped Entities with Java Records

Create a Micronaut Data Mapped Entity

java/src/main/java/example/micronaut/Book.java

Projections with Java Records

Create a record to project some data from the book table. For example, exclude the about field.

java/src/main/java/example/micronaut/BookCard.java

Create a Repository, which uses the previous Java record as a DTO projection.

java/src/main/java/example/micronaut/BookRepository.java

JSON serialization with Java Records

Create a Java record to represent a JSON response:

java/src/main/java/example/micronaut/BookForSale.java

Create a Controller that uses the previous record:

java/src/main/java/example/micronaut/BookController.java

Create a Test

Create a test:

java/src/test/java/example/micronaut/BookControllerTest.java

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 PostgreSQL docker container, and inject the properties required to use this as the datasource.

For more information, see the JDBC section of the Test Resources documentation.

Datasource configuration

Although the URL is configured automatically via Test Resources, we must configure the PostgreSQL driver and dialect in application.properties:

java/src/main/resources/application.properties

Testing the Application

To run the tests:

./mvnw test

Running the application

Set up the environment variable to configure the VAT percentage.

Configure

export VAT_PERCENTAGE=20

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

You can run a cURL command to test the application:

curl http://localhost:8080/books
[{"isbn":"0321601912","title":"Continuous Delivery","price":47.99}]

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.

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

GraalVM Installation

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

Java 25
sdk install java 25.0.2-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 25
sdk install java 25.0.2-graalce

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

pom.xml

You can run a cURL command to test the application:

curl http://localhost:8080/books
[{"isbn":"0321601912","title":"Continuous Delivery","price":47.99}]

You receive an empty array because there are no books in the database. You can create a Liquibase changelog to add seed data.

Next Steps

Explore more features with Micronaut Guides.

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