Warm tip: This article is reproduced from stackoverflow.com, please click
flyway spring-boot

Multiple datasources migrations using Flyway in a Spring Boot application

发布于 2020-04-22 10:42:29

We use Flyway for db migration in our Spring Boot based app and now we have a requirement to introduce multi tenancy support while using multiple datasources strategy. As part of that we also need to support migration of multiple data sources. All data sources should maintain the same structure so same migration scripts should be used for migrating of all data sources. Also, migrations should occur upon application startup (as opposed to build time, whereas it seems that the maven plugin can be configured to migrate multiple data sources). What is the best approach to use in order to achieve this? The app already has data source beans defined but Flyway executes the migration only for the primary data source.

Questioner
Eli Avzak
Viewed
335
5,534 2020-02-11 22:33

Flyway supports migrations coded within Java and so you can start Flyway during your application startup.

https://flywaydb.org/documentation/migration/java

I am not sure how you would config Flyway to target a number of data sources via the its config files. My own development is based around using Java to call Flyway once per data source I need to work against. Spring Boot supports the autowiring of beans marked as @FlywayDataSource, but I have not looked into how this could be used.

For an in-java solution the code can be as simple as

    Flyway flyway = new Flyway();

    // Set the data source
    flyway.setDataSource(dataSource);

    // Where to search for classes to be executed or SQL scripts to be found
    flyway.setLocations("net.somewhere.flyway");

    flyway.setTarget(MigrationVersion.LATEST);
    flyway.migrate();