Micronaut Data and Java Records
Learn how to leverage Java records for immutable configuration, Micronaut Data Mapped Entities and Projection DTOs
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:
-
Some time on your hands
-
A decent text editor or IDE (e.g. IntelliJ IDEA)
-
JDK 21 or greater installed with
JAVA_HOMEconfigured appropriately
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.
-
Download and unzip the source
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
Write a test:
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:
<dependency>
<groupId>io.micronaut.liquibase</groupId>
<artifactId>micronaut-liquibase</artifactId>
<scope>compile</scope>
</dependency>Configure the database migrations directory for Liquibase in application.properties.
liquibase.enabled=true
liquibase.datasources.default.change-log=classpath:db/liquibase-changelog.xmlCreate the following files with the database schema creation and a book:
<?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><?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><?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
Projections with Java Records
Create a record to project some data from the book table. For example, exclude the about field.
Create a Repository, which uses the previous Java record as a DTO projection.
JSON serialization with Java Records
Create a Java record to represent a JSON response:
Create a Controller that uses the previous record:
Create a Test
Create a 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 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:
Testing the Application
To run the tests:
./mvnw testRunning the application
Set up the environment variable to configure the VAT percentage.
Configure
export VAT_PERCENTAGE=20To 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
sdk install java 25.0.2-graalFor 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:
sdk install java 25.0.2-graalceNative Executable Generation
To generate a native executable using Maven, run:
./mvnw package -Dpackaging=native-imageThe 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:
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). |