An app that uses Gradle and flyway for database migration I made a trial and error when I wrote the callback in Java.
The bottom line is that you should 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
ʻOrg.flywaydb.core.api.callback.Callback` Create a class that implements the interface Set the flyway.callbacks property to a fully qualified name. https://flywaydb.org/documentation/api/hooks#java-based-callbacks
Also, make sure that the classes task is executed before the flyway task. * This is important </ b> (To be exact, is it a compile Java 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 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)
When you execute the migration, you can see that the insert statement has been executed.
This method was taught by a person inside the flyway. https://github.com/flyway/flyway/issues/2829
Recommended Posts