[Java] Write flyway callback in Java

1 minute read


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


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?)


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 {

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

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

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


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

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


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