Java-based migrations
Published 19 December 2024
Java-based migrations are a great fit for all changes that can not easily be expressed using SQL.
These would typically be things like
- BLOB & CLOB changes
- Advanced bulk data changes (Recalculations, advanced format changes, ...)
Note: Java-based migrations are not currently supported by Native Connectors.
In order to be picked up by Flyway, Java-based Migrations must implement the JavaMigration
interface. Most users however should inherit from the convenience class BaseJavaMigration
instead as it encourages Flyway's default naming convention, enabling Flyway to automatically extract the version and the description from the class name.
Java migrations must match the same naming conventions as SQL migrations, excepting the suffix.
Checksums and Validation
Unlike SQL migrations, Java migrations by default do not have a checksum and therefore do not participate in the change detection of Flyway's validation. This can be remedied by implementing the getChecksum()
method, which you can then use to provide your own checksum, which will then be stored and validated for changes.
Sample Class
package db.migration;
import org.flywaydb.core.api.migration.BaseJavaMigration;
import org.flywaydb.core.api.migration.Context;
import java.sql.PreparedStatement;
/**
* Example of a Java-based migration.
*/
public class V1_2__Another_user extends BaseJavaMigration {
public void migrate(Context context) throws Exception {
try (PreparedStatement statement =
context
.getConnection()
.prepareStatement("INSERT INTO test_user (name) VALUES ('Obelix')")) {
statement.execute();
}
}
}
Take care that your Java migration does not close the database connection, either explicitly or as a result of a try-with-resources statement.
Spring
If your application already uses Spring and you do not want to use JDBC directly you can easily use Spring JDBC's JdbcTemplate
instead:
package db.migration;
import org.flywaydb.core.api.migration.BaseJavaMigration;
import org.flywaydb.core.api.migration.Context;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
/**
* Example of a Java-based migration using Spring JDBC.
*/
public class V1_2__Another_user extends BaseJavaMigration {
public void migrate(Context context) {
new JdbcTemplate(new SingleConnectionDataSource(context.getConnection(), true))
.execute("INSERT INTO test_user (name) VALUES ('Obelix')");
}
}