Using Liquibase and Flyway for multiple databases (programmatic approach)

Robert Diers
NEW IT Engineering
Published in
2 min readMay 28, 2021

--

Purpose of this document

I do not want to introduce Flyway or Liquibase, that is a ton of material available for it.

But I want to share my approach how to use these tools in combination or how to use more than one database within the same application.

Problem

Perfect integration comes with problems, so it is really easy to integrate Flyway with Spring Boot but you might face issues when integrating a second database or when trying to reuse existing configurations for existing databases.

Combine Flyway and Liquibase?

Yes it worked for me without problems, nothing else to mention here.

How to apply migrations in code?

We do need a way to use existing configuration and to execute multiple migrations at startup. (please do not use Spring Boot starters here)

First of all I decided to have a central class using the tools to migrate a specific “folder” — a folder is one database representation in my case.

All of my database migration files are stored in resources/db.

Now we can create a class for every database doing the migration during initialization using existing configuration / connections.

Cassandra example:

Oracle example:

Sorry to give this central class code a bit unformated:

/**
* base for database migrations
*/
@Slf4j
public class BaseDatabaseMigration {

protected void migrateFlyway(String folder, DataSource ds) {
try {
// Create the Flyway instance and point it to the database
Flyway flyway = Flyway.configure()
.baselineOnMigrate(true) //required because of existing objects
.dataSource(ds)
.locations("db/"+folder)
.load();
// Start the migration
flyway.migrate();

} catch (Exception e) {
log.error("failed to migrate db (Flyway): "+folder, e);
//need to stop the app
System.exit(1);
}
}
protected void migrateLiquibase(String folder, String schema, Connection con) {
try {
// Create the Liquibase Database and update
Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(con));
database.setDefaultSchemaName(schema);
Liquibase liquibase = new liquibase.Liquibase("db/"+folder+"/db.changelog-master.xml", new ClassLoaderResourceAccessor(), database);
liquibase.update(new Contexts(), new LabelExpression());
} catch (Exception e) {
log.error("failed to migrate db (Liquibase): "+folder, e);
//need to stop the app
System.exit(1);
}
}

}

--

--