Sub topic 11
Java-based migrations
Some schema changes are awkward or impossible to express in plain SQL. Flyway lets you write those changes in Java instead. This chapter covers when to choose a Java migration, how to name and place one, how to run it safely, and the edge cases that cause trouble.
It assumes you have read the chapters on versioned SQL migrations and on the flyway_schema_history table. You should also be comfortable with JDBC (Connection, Statement, PreparedStatement).
When SQL is not enough
A SQL migration is the default choice. It is easy to review, and a database administrator can run it by hand. Reach for Java only when the change needs logic that SQL cannot express well. Typical cases:
- Transforming data row by row with application rules, such as normalizing phone numbers or splitting a full name into parts.
- Calling a library, for example hashing values or parsing JSON, where a database function does not exist.
- Reading data in one step and writing it in another, with branching in between.
- Generating many statements from existing data, such as creating one table per tenant.
The example in this tutorial is small. The app_user table gained a display_name column in V2, and now existing rows need a value. A one-line UPDATE would do this. Real backfills are often not that simple, which is why the pattern matters.
Anatomy of a Java migration
A Java migration is a class that extends BaseJavaMigration. Flyway finds it on the classpath, reads the version and description from its class name, and calls its migrate method.
package db.migration;
import java.sql.Statement;
import org.flywaydb.core.api.migration.BaseJavaMigration;
import org.flywaydb.core.api.migration.Context;
public class V3__Backfill_display_name extends BaseJavaMigration {
@Override
public void migrate(Context context) throws Exception {
try (Statement st = context.getConnection().createStatement()) {
st.execute("UPDATE app_user SET display_name = username WHERE display_name IS NULL");
}
}
}Four rules make this work:
- The class lives in the
db.migrationpackage. Flyway scans the locations you configure, and the defaultclasspath:db/migrationalso covers the packagedb.migration. - The class name follows the same pattern as a SQL file:
V<version>__<description>, with two underscores. Here the version is3and the description isBackfill display name. Underscores in the description become spaces. - The class is public and has a public no-argument constructor. Flyway creates it by reflection.
- The version must fit in the same sequence as your SQL migrations.
V3runs afterV2whetherV2is a.sqlfile or a Java class.
Naming for repeatable Java migrations
A Java migration can also be repeatable. Name the class R__<description> and Flyway treats it like an R__ SQL file. Because a Java class has no file contents to hash, a repeatable Java migration should override getChecksum(). Without it, Flyway records a null checksum and never re-applies the migration after the first run.
What the Context gives you
The Context argument exposes two things.
| Method | Returns | Use it for |
|---|---|---|
| `getConnection()` | A JDBC `Connection` | Running statements in the migration's transaction |
| `getConfiguration()` | The Flyway `Configuration` | Reading settings such as placeholders |
The connection belongs to Flyway. Do not close it, and do not call commit() or rollback() on it yourself. Flyway manages the transaction around your migrate method. Closing the connection ends the migration run with an error. Closing only the Statement or PreparedStatement objects you created, as the example does with try-with-resources, is correct.
A more realistic example: row-by-row backfill
The first example could be one SQL statement. This one applies a rule that SQL cannot express as cleanly. It builds a display name from the username by capitalizing each word, and it uses a PreparedStatement with batching.
package db.migration;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Locale;
import org.flywaydb.core.api.migration.BaseJavaMigration;
import org.flywaydb.core.api.migration.Context;
public class V4__Capitalize_display_name extends BaseJavaMigration {
private static final int BATCH_SIZE = 500;
@Override
public void migrate(Context context) throws Exception {
String select = "SELECT id, username FROM app_user";
String update = "UPDATE app_user SET display_name = ? WHERE id = ?";
try (Statement read = context.getConnection().createStatement();
ResultSet rows = read.executeQuery(select);
PreparedStatement write = context.getConnection().prepareStatement(update)) {
int pending = 0;
while (rows.next()) {
write.setString(1, capitalize(rows.getString("username")));
write.setLong(2, rows.getLong("id"));
write.addBatch();
if (++pending == BATCH_SIZE) {
write.executeBatch();
pending = 0;
}
}
if (pending > 0) {
write.executeBatch();
}
}
}
private static String capitalize(String username) {
StringBuilder out = new StringBuilder();
for (String part : username.split("[._-]+")) {
if (part.isEmpty()) {
continue;
}
if (out.length() > 0) {
out.append(' ');
}
out.append(part.substring(0, 1).toUpperCase(Locale.ROOT))
.append(part.substring(1).toLowerCase(Locale.ROOT));
}
return out.toString();
}
}The code reads and writes on the same connection. Some drivers do not allow a second statement while a result set is still open. PostgreSQL's JDBC driver fetches the whole result set into memory by default, so it works here. For very large tables, read in pages (for example WHERE id > ? ORDER BY id LIMIT 1000) instead of loading everything, or the migration can exhaust memory.
How Flyway runs a Java migration
A Java migration goes through the same path as a SQL one. The diagram shows the order inside a single run.
Flyway records the result in flyway_schema_history in the same way as for SQL. The type column holds JDBC for a Java migration and SQL for a SQL one. This helps when you read the history table to see how a change was applied.
Transactions and failure
By default Flyway wraps each migration in one transaction. If migrate throws an exception, Flyway rolls back and the history row is not written as a success. This holds on databases that support transactional DDL, such as PostgreSQL. On a database without it, such as MySQL, DDL statements commit implicitly, so a failed migration can leave partial changes behind.
Two consequences follow:
- Let exceptions propagate. Do not catch
SQLExceptionand continue. A swallowed error leaves the data half-converted while Flyway records the migration as done. - Keep a Java migration idempotent in spirit where you can. The
WHERE display_name IS NULLclause inV3means a re-run would not overwrite values, which makes recovery easier.
If a statement cannot run inside a transaction (for example CREATE INDEX CONCURRENTLY on PostgreSQL), override canExecuteInTransaction() and return false:
@Override
public boolean canExecuteInTransaction() {
return false;
}With this set, a failure no longer rolls back automatically. Write such a migration so that it can be re-run safely.
Checksums for Java migrations
A SQL migration has a checksum computed from its file contents. A Java class has no such file. BaseJavaMigration returns null from getChecksum() unless you override it. This has a direct effect on validation:
- With no checksum, Flyway cannot notice that you edited the class after it was applied. Validation will not warn you.
- The reverse mistake is also possible. If you change the class, the history still matches because both sides have
null.
You can supply a checksum yourself, for example from a constant you bump when the logic changes:
@Override
public Integer getChecksum() {
return 2; // bump this whenever the migration logic changes
}Treat applied Java migrations the same as applied SQL ones. Never edit them. Add a new, higher-numbered migration for any further change.
Spring beans and dependency injection
A common question is whether a Java migration can use Spring beans such as a JdbcTemplate or a service class. A class found by classpath scanning is created by Flyway through reflection, not by Spring, so @Autowired does nothing there.
There is a supported alternative. Flyway's Spring Boot integration picks up JavaMigration beans from the application context. If you declare the migration as a Spring bean, Spring creates it and can inject dependencies. Two cautions apply:
- Flyway runs before most application beans are ready, and Spring Boot makes the
Flywaybean a dependency of the JPA entity manager factory. A migration bean that depends on a repository or an entity manager creates a circular dependency and the application fails to start. - Migrations that use application services are tied to the code of that day. When the service changes next year, an old migration may behave differently or fail to compile.
For these reasons, write migrations with plain JDBC against the Context connection and avoid application classes. A migration should still produce the same result when run on a new database two years from now.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Class is never run | Wrong package or location not scanned | Put it in `db.migration`, or add its package to `spring.flyway.locations` |
| `Invalid Java migration class name` style error | Single underscore or missing `V` | Use `V3__Description`, two underscores |
| Version conflict on startup | Same version used by a SQL file and a Java class | Give each migration a unique version |
| Connection closed error | You closed `context.getConnection()` | Close only your own statements and result sets |
| Edited class not detected | `getChecksum()` returns `null` | Override `getChecksum()` and bump it on change |
| Circular dependency at startup | Migration is a bean that needs JPA beans | Use plain JDBC and drop injected application beans |
Testing a Java migration
You test a Java migration like any other. Start the application context against a real test database, such as PostgreSQL in a container, and confirm that Flyway applied everything. The test from the testing chapter also covers Java classes:
import org.flywaydb.core.Flyway;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
@SpringBootTest
class MigrationsTest {
@Autowired
Flyway flyway;
@Test
void allMigrationsAreApplied() {
assertEquals(0, flyway.info().pending().length);
}
}This only proves that the migration ran without error. To check the data change, insert a few rows at an earlier version, migrate to the target, and assert on the result. Flyway supports this through target: configure a Flyway instance with .target("2"), load test rows, then migrate to 3 and query.
Summary of decisions
- Use SQL for schema changes and simple data changes.
- Use Java when you need logic, loops, or libraries, and keep it to plain JDBC.
- Name the class
V<version>__<description>indb.migration. - Do not close the connection or manage the transaction.
- Override
getChecksum()if you want edits detected. - Never edit a migration after it has been applied.
Exercise
You wrote V5__Normalize_phone_numbers as a Java migration and it ran in production. Later you find a bug in the normalization rule. A teammate suggests fixing the class in place, because Flyway will not complain. Why is this a bad idea, and what should you do instead?
Show answer
Flyway will not complain only because BaseJavaMigration returns a null checksum, so validation cannot detect the edit. The fix would still not run on databases that already applied V5, so production and new environments would end up with different data. Leave V5 unchanged and add V6__Fix_phone_number_normalization that corrects the data already stored. A fresh database then runs V5 and V6 in order and reaches the same result as production.
Exercise
A Java migration needs to read thousands of rows and update each one. A colleague wants to inject a Spring Data repository into it. Give two reasons to use context.getConnection() with JDBC instead.
Show answer
First, Flyway runs before the JPA infrastructure is ready, and a migration bean that depends on a repository creates a circular dependency that stops startup. Second, a migration that depends on application classes can break or change behavior when those classes change later, so it no longer produces the same result on a fresh database. Plain JDBC on the context connection also joins Flyway's transaction.