Sample of a simple Micronaut CRUD application using Micronaut Data and supporting Oracle's GraalVM/SubstrateVM.
The example contains a Footballmanager microservice which accesses a PostgreSQL and provides the data via REST/JSON.
To create a new Footballer a POST request needs to be submitted to the REST endpoint http://localhost:8080/footballers
:
{
"firstName": "Toni",
"lastName": "Kroos",
"position": "Midfield"
}
All existing Footballers can be retrieved be sending a GET request to http://localhost:8080/footballers
.
With the optional request parameter position
all Footballers of a certain position are determined
(e.g. http://localhost:8080/footballers?position=Midfield
).
The PostgreSQL should be running on jdbc:postgresql://localhost:5432/footballerdb
.
See below how to setup a dockerized PostgreSQL.
Building the Fat-/Uber-Jar with Gradle:
./gradlew clean shadowJar
Executing the JAR via:
java -jar build/libs/footballermanager-0.1-all.jar
(Or you just start the Application.kt
in your IDE).
How to build a native image of the application with GraalVM/SubstrateVM (installation see below).
Using GraalVM’s native-image
tool:
sdk use java 21.2.0.r11-grl
./gradlew clean assemble
native-image --no-server -cp build/libs/footballermanager-0.1-all.jar
Executing the native image via:
./footballermanager
Using Micronaut's Gradle Plugin:
Since Micronaut 2.1.0 you can delegate the native image generation to Micronaut's Gradle Plugin:
sdk use java 21.2.0.r11-grl
./gradlew nativeImage
Executing the native image via:
./build/native-image/application
To manage SDK versions on your local machine SDKMAN! is a very helpful tool.
Oracle's GraalVM can be installed with sdk install java 21.2.0.r11-grl
(or appropriate version).
If you don't want to use Micronaut's Gradle Plugin
you have to install GraalVM’s native-image
tool
with the command gu install native-image
.
Execute the following steps:
docker pull postgres
docker run -p 5432:5432 --name postgres-db -e POSTGRES_PASSWORD=mysecretpassword -d postgres
docker exec -it postgres-db bash
psql -U postgres
CREATE DATABASE footballerdb;
Problem: The first request after starting the app results in an error like this:
{
"message": "Internal Server Error: SQL Error executing Query: ERROR: relation \"footballer\" does not exist\n Position: 102"
}
Solution: Please make sure these properties are set in the application.yaml
so that the table footballer
is created:
datasources:
default:
schema-generate: CREATE # or CREATE_DROP if you want the table to be re-created with each app start
dialect: postgres