mn create-app example.micronaut.micronautguide \
--features=data-jdbc,mysql,flyway \
--build=gradle --lang=java
Schema Migration with Flyway
Learn how to use Flyway to manage your schema migrations
Authors: Sergio del Amo
Micronaut Version: 4.6.3
1. Getting Started
In this guide, we will create a Micronaut application written in Java.
You use Flyway:
Flyway is an open-source database migration tool. It strongly favors simplicity and convention over configuration.
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 (e.g. IntelliJ IDEA)
-
JDK 17 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.
-
Download and unzip the source
Create an application using the Micronaut Command Line Interface or with Micronaut Launch.
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 mysql , data-jdbc , and flyway as features.
|
3.1. Create Entity
Create a @MappedEntity
to save persons. Initially, consider name and age required. Use int
primitive for the age.
package example.micronaut;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.data.annotation.GeneratedValue;
import io.micronaut.data.annotation.Id;
import io.micronaut.data.annotation.MappedEntity;
import io.micronaut.data.annotation.Version;
import jakarta.validation.constraints.NotBlank;
@MappedEntity (1)
public class Person {
@Id (2)
@GeneratedValue (3)
private Long id;
@Version (4)
private Long version;
@NonNull
@NotBlank
private final String name;
private final int age;
public Person(@NonNull String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
@NonNull
public String getName() {
return name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
}
1 | Annotate the class with @MappedEntity to map the class to the table defined in the schema. |
2 | Specifies the ID of an entity |
3 | Specifies that the property value is generated by the database and not included in inserts |
4 | Annotate the field with @Version to enable optimistic locking for your entity. |
3.2. Database Migration with Flyway
We need a way to create the database schema. For that, we use Micronaut integration with Flyway.
Flyway automates schema changes, significantly simplifying schema management tasks, such as migrating, rolling back, and reproducing in multiple environments.
Add the following snippet to include the necessary dependencies:
implementation("io.micronaut.flyway:micronaut-flyway")
We will enable Flyway in the Micronaut configuration file and configure it to perform migrations on one of the defined data sources.
(1)
flyway.datasources.default.enabled=true
1 | Enable Flyway for the default datasource. |
Configuring multiple data sources is as simple as enabling Flyway for each one. You can also specify directories that will be used for migrating each data source. Review the Micronaut Flyway documentation for additional details. |
Flyway migration will be automatically triggered before your Micronaut application starts. Flyway will read migration commands in the resources/db/migration/
directory, execute them if necessary, and verify that the configured data source is consistent with them.
Create the following migration files with the database schema creation:
CREATE TABLE person(
id bigint primary key not null,
name varchar(255) not null,
age int not null
)
During application startup, Flyway executes the SQL file and creates the schema needed for the application.
If you check the database schema, there are two tables:
-
person
-
flyway_scheme_history
Flyway uses the table flyway_scheme_history
to keep track of database migrations.
The person
table looks like:
Column | Nullable |
---|---|
|
NO |
|
NO |
|
NO |
|
NO |
3.3. Drop Not Null Constraint
Applications change. Make age
optional:
@Nullable
private final Integer age;
public Person(@NonNull String name,
@Nullable Integer age) {
this.name = name;
this.age = age;
}
@Nullable
public Integer getAge() {
return age;
}
Add a new migration to drop the null constraint:
ALTER TABLE person MODIFY age int default null;
After the migration, the person
table looks like:
Column | Nullable |
---|---|
|
NO |
|
NO |
|
NO |
|
YES |
4. Flyway endpoint
To enable the Flyway endpoint, add the management
dependency on your classpath.
implementation("io.micronaut:micronaut-management")
Enable the Flyway endpoint:
endpoints.flyway.enabled=true
endpoints.flyway.sensitive=false
4.1. Test
Create a test that invokes the Flyway endpoint.
package example.micronaut;
import io.micronaut.core.type.Argument;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.client.BlockingHttpClient;
import io.micronaut.http.client.HttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.util.List;
import static io.micronaut.http.HttpStatus.OK;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@MicronautTest (1)
public class FlywayEndpointTest {
@Inject
@Client("/") (2)
HttpClient httpClient;
@Test
void migrationsAreExposedViaAndEndpoint() {
BlockingHttpClient client = httpClient.toBlocking();
HttpResponse<List<FlywayReport>> response = client.exchange(
HttpRequest.GET("/flyway"),
Argument.listOf(FlywayReport.class));
assertEquals(OK, response.status());
List<FlywayReport> flywayReports = response.body();
assertNotNull(flywayReports);
assertEquals(1, flywayReports.size());
FlywayReport flywayReport = flywayReports.get(0);
assertNotNull(flywayReport);
assertNotNull(flywayReport.getMigrations());
assertEquals(2, flywayReport.getMigrations().size());
}
static class FlywayReport {
private List<Migration> migrations;
public void setMigrations(List<Migration> migrations) {
this.migrations = migrations;
}
public List<Migration> getMigrations() {
return migrations;
}
}
static class Migration {
private String script;
public void setId(String script) {
this.script = script;
}
public String getScript() {
return script;
}
}
}
1 | Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context and the embedded server. More info. |
2 | Inject the HttpClient bean and point it to the embedded server. |
5. Test Resources
When the application is started locally — either under test or by running the application — 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.
6. Testing the Application
To run the tests:
./gradlew test
Then open build/reports/tests/test/index.html
in a browser to see the results.
7. Running the Application
To run the application, use the ./gradlew run
command, which starts the application on port 8080.
You can run a cURL command to test the application:
curl http://localhost:8080/flyway
You will see information about migrations.
8. Generate a Micronaut Application Native Executable with GraalVM
We will use GraalVM, the polyglot embeddable virtual machine, to generate a native executable of our Micronaut application.
Compiling native executables ahead of time with GraalVM improves startup time and reduces the memory footprint of JVM-based applications.
Only Java and Kotlin projects support using GraalVM’s native-image tool. Groovy relies heavily on reflection, which is only partially supported by GraalVM.
|
8.1. GraalVM installation
sdk install java 21.0.5-graal
sdk use java 21.0.5-graal
For installation on Windows, or for 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 21.0.2-graalce
sdk use java 21.0.2-graalce
8.2. Native executable generation
To generate a native executable using Gradle, run:
./gradlew nativeCompile
The native executable is created in build/native/nativeCompile
directory and can be run with build/native/nativeCompile/micronautguide
.
It is possible to customize the name of the native executable or pass additional parameters to GraalVM:
graalvmNative {
binaries {
main {
imageName.set('mn-graalvm-application') (1)
buildArgs.add('--verbose') (2)
}
}
}
1 | The native executable name will now be mn-graalvm-application |
2 | It is possible to pass extra arguments to build the native executable |
You can run a cURL command to test the application:
curl http://localhost:8080/flyway
You will see information about migrations.
9. Next steps
Explore more features with Micronaut Guides.
Check Micronaut Flyway integration.
Learn more about Flyway.
10. Help with the Micronaut Framework
The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.
11. License
All guides are released with an Apache license 2.0 license for the code and a Creative Commons Attribution 4.0 license for the writing and media (images…). |