Schema Migration with Liquibase

Learn how to use the Liquibase 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 Kotlin.

2. What you will need

To complete this guide, you will need the following:

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.

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

mn create-app
   example.micronaut.micronautguide \
   --features=data-jdbc,postgres,liquibase \
   --build=maven \
   --lang=kotlin \
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 postgres, data-jdbc, and liquibase as features.

3.1. Create Entity

Create a @MappedEntity to save persons. Initially, consider name and age required. Use int primitive for the age.

src/main/kotlin/example/micronaut/Person.kt
package example.micronaut


import io.micronaut.data.annotation.GeneratedValue
import io.micronaut.data.annotation.Id
import io.micronaut.data.annotation.MappedEntity
import io.micronaut.data.annotation.Version

@MappedEntity (1)
class Person(
    val name: String,

    val age: Int

) {

    @Id (2)
    @GeneratedValue (3)
    var id: Long? = null

    @Version (4)
    var version: Long? = null
}
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 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.

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

Create the following files with the database schema creation:

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-person.xml"
             relativeToChangelogFile="true"/>

    <include file="changelog/02-nullable-age.xml"
             relativeToChangelogFile="true"/>

</databaseChangeLog>
src/main/resources/db/changelog/01-create-person.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="person"
                     remarks="A table to contain persons">

            <column name="id" type="BIGINT">
                <constraints nullable="false"
                             unique="true"
                             primaryKey="true"
                             primaryKeyName="personPK"/>
            </column>

            <column name="version" type="BIGINT">
                <constraints nullable="false"/>
            </column>

            <column name="age" type="INT">
                <constraints nullable="false"/>
            </column>

        </createTable>

    </changeSet>

</databaseChangeLog>

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

If you check the database schema, there are three tables:

  • databasechangelog

  • databasechangeloglock

The tables databasechangelog and databasechangeloglock are used by Liquibase to keep track of database migrations.

The person table looks like:

Column Nullable

id

NO

version

NO

name

NO

age

NO

3.3. Drop Not Null Constraint

Applications change. Make age optional:

src/main/kotlin/example/micronaut/Person.kt
    val age: Int?

Add a new changeset to drop the null constraint:

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-person.xml"
             relativeToChangelogFile="true"/>

    <include file="changelog/02-nullable-age.xml"
             relativeToChangelogFile="true"/>

</databaseChangeLog>
src/main/resources/db/changelog/02-nullable-age.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">
        <dropNotNullConstraint tableName="person"
                               columnName="age"/>
    </changeSet>

</databaseChangeLog>

After the changeset, the person table looks like:

Column Nullable

id

NO

version

NO

name

NO

age

YES

4. Liquibase

To enable the Liquibase endpoint, add the management dependency on your classpath.

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

Enable the Liquibase endpoint:

src/main/resources/application.properties
endpoints.liquibase.sensitive=false

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

5.1. Test

Create a test that invokes the Liquibase endpoint

src/test/kotlin/example/micronaut/LiquibaseEndpointTest.kt
package example.micronaut

import io.micronaut.core.type.Argument
import io.micronaut.http.HttpRequest
import io.micronaut.http.HttpStatus.OK
import io.micronaut.http.client.HttpClient
import io.micronaut.http.client.annotation.Client
import io.micronaut.serde.annotation.Serdeable
import io.micronaut.test.extensions.junit5.annotation.MicronautTest
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Test

@MicronautTest (1)
class LiquibaseEndpointTest(@Client("/") val httpClient: HttpClient) { (2)

    @Test
    fun migrationsAreExposedViaAndEndpoint() {
        val client = httpClient.toBlocking()

        val response = client.exchange(HttpRequest.GET<Any>("/liquibase"), Argument.listOf(LiquibaseReport::class.java))
        assertEquals(OK, response.status())

        val liquibaseReport = response.body().get(0)
        assertNotNull(liquibaseReport)
        assertNotNull(liquibaseReport!!.changeSets)
        assertEquals(2, liquibaseReport.changeSets!!.size)
    }
}

@Serdeable
class LiquibaseReport {
    var changeSets: List<ChangeSet>? = null
}

@Serdeable
class ChangeSet {
    var id: String? = null
}
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.2. Running the application

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

src/main/resources/application.properties
(1)
datasources.default.driver-class-name=org.postgresql.Driver
(2)
datasources.default.dialect=POSTGRES
(3)
datasources.default.schema-generate=NONE
1 Use PostgreSQL driver.
2 Configure the PostgreSQL dialect.
3 You handle database migrations via Liquibase

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/liquibase

You will see information about migrations.

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

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

6.1. GraalVM Installation

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

Java 21
sdk install java 21.0.5-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 21
sdk install java 21.0.2-graalce

6.2. 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 following:

pom.xml
<plugin>
    <groupId>org.graalvm.buildtools</groupId>
    <artifactId>native-maven-plugin</artifactId>
    <version>0.10.3</version>
    <configuration>
        <!-- <1> -->
        <imageName>mn-graalvm-application</imageName> (1)
        <buildArgs>
              <!-- <2> -->
          <buildArg>-Ob</buildArg>
        </buildArgs>
    </configuration>
</plugin>
1 The native executable name will now be mn-graalvm-application.
2 It is possible to pass extra build arguments to native-image. For example, -Ob enables the quick build mode.

You can run a cURL command to test the application:

curl http://localhost:8080/liquibase

You will see information about migrations.

7. Next Steps

Explore more features with Micronaut Guides.

Check Micronaut Liquibase integration.

8. Help with the Micronaut Framework

The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.

9. 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…​).