如何用Flyway和Spring Boot迁移生命周期不同的多Schema?
Hey there! From your setup description, your project falls perfectly into Flyway’s third multi-schema category: "Schemas with different lifecycles or requiring independent isolation". Since each Maven module is fully independent with its own dedicated schema (all hosted on the same database using a single data source), here’s how you can manage separate migration lifecycles for each:
Step 1: Configure Flyway per Module
Each module needs its own isolated Flyway configuration in its pom.xml. Add the Flyway Maven plugin with settings targeting the module’s specific schema:
<plugin> <groupId>org.flywaydb</groupId> <artifactId>flyway-maven-plugin</artifactId> <version><!-- Use a version compatible with Spring Boot 4.5.9 --></version> <configuration> <url>${spring.datasource.url}</url> <user>${spring.datasource.username}</user> <password>${spring.datasource.password}</password> <defaultSchema>[your_module_schema_name]</defaultSchema> <locations>filesystem:src/main/resources/db/migration/[your_module_schema_name]</locations> </configuration> <executions> <execution> <goals> <goal>migrate</goal> </goals> </execution> </executions> </plugin>
- Replace
[your_module_schema_name]with the actual schema assigned to each module. - Keep database credentials consistent across modules since you’re using a single shared data source.
Step 2: Isolate Migration Scripts per Module
For each module, create a dedicated directory structure to house its migration scripts. This ensures changes to one module’s schema never interfere with another:
module-users/ └── src/ └── main/ └── resources/ └── db/ └── migration/ └── schema_users/ ├── V1__initial_user_setup.sql └── V2__add_user_profile_table.sql module-products/ └── src/ └── main/ └── resources/ └── db/ └── migration/ └── schema_products/ ├── V1__create_product_catalog.sql └── V2__add_inventory_tracking.sql
Step 3: Run Migrations Independently
Thanks to per-module Flyway configurations, you can trigger migrations for a single module by running the Maven goal from its directory:
cd module-users mvn flyway:migrate
To run migrations for multiple modules at once from the parent project, use the -pl flag to specify target modules:
mvn flyway:migrate -pl module-users,module-products
Step 4: Auto-Run Migrations on App Startup (Optional)
If you want migrations to execute automatically when the Spring Boot app starts, add module-specific Flyway settings to each module’s application.properties:
# module-users/application.properties spring.flyway.enabled=true spring.flyway.default-schema=schema_users spring.flyway.locations=classpath:db/migration/schema_users
This ensures each module’s Flyway instance runs its own migrations against its schema on application startup—just make sure module configurations are scoped to avoid conflicts.
Pro tip: Ensure your database user has sufficient permissions to create, modify, and manage objects in all target schemas.
内容的提问来源于stack exchange,提问作者MatanRubin

