[Java] Write flyway callback in Java

1 minute read

Introduction

In an app that uses Gradle and flyway for database migration I tried and error when writing the callback in Java.

The bottom line is to compile the Callback class before executing the flyway task.

Please refer to the following repository for the code verified this time. https://github.com/mahaker/flyway-callback-java

Environment

Java: OpenJDK 11 Gradle: 5.2.1 flyway: 6.4.2 Postgres: 12

Writing the callback in Java

Create a class that implements the org.flywaydb.core.api.callback.Callback interface Set the flyway.callbacks property to the fully qualified name. https://flywaydb.org/documentation/api/hooks#java-based-callbacks

Also, execute the classes task before the flyway task. *This is important (To be exact, compileJava task?)

FillTestData.java


package db.migration;

import java.sql.PreparedStatement;

import org.flywaydb.core.api.callback.Callback;
import org.flywaydb.core.api.callback.Context;
import org.flywaydb.core.api.callback.Event;

public class FillTestData implements Callback {

    @Override
    public boolean supports(Event event, Context context) {
        return Event.AFTER_MIGRATE.equals(event);
    }

    @Override
    public boolean canHandleInTransaction(Event event, Context context) {
        return false;
    }

    @Override
    public void handle(Event event, Context context) {
        try (
            final PreparedStatement statement = context
                .getConnection()
                .prepareStatement("INSERT INTO PERSON(ID, NAME, AGE) VALUES (1,'userA', 20), (2,'userB', 22)")
        ) {
            statement.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

build.gradle


// Excerpt of only what you need
plugins {
    id "org.flywaydb.flyway" version "6.4.2"
}

group'org.example'
version '1.0-SNAPSHOT'

sourceCompatibility = 11

flyway {
    url ='jdbc:postgresql://localhost:15432/exampledb'
    user ='postgres'
    password ='example'
    locations = ['filesystem:./src/main/resources/db/migration/']
    callbacks = ['db.migration.FillTestData']
}

//!! Important! !!
flywayClean.dependsOn(classes)
flywayMigrate.dependsOn(classes)

Summary

You can confirm that the insert statement is executed by executing migration.

This method was taught by a person on the flyway. https://github.com/flyway/flyway/issues/2829