How do you implement database migrations with Flyway in Spring Boot?
Table of Contents
Introduction
Database migrations ensure a consistent schema across environments as your application evolves. Flyway is a powerful tool for managing database versioning and migrations in Spring Boot applications. This guide explains how to integrate Flyway, write migration scripts, and execute migrations efficiently.
Steps to Implement Flyway in Spring Boot
1. Adding Flyway Dependency
First, add the Flyway dependency to your Spring Boot project. If you are using Maven, include the following in your pom.xml
:
For Gradle, add this to your build.gradle
:
2. Configuring Flyway in application.properties
Flyway integrates seamlessly with Spring Boot. Basic configurations can be defined in application.properties
or application.yml
.
Example: Basic Configuration
spring.flyway.enabled
: Enables Flyway migrations.spring.flyway.locations
: Specifies the folder for migration scripts.spring.flyway.baseline-on-migrate
: Ensures existing databases are marked with a baseline version.
3. Writing Migration Scripts
Flyway executes migration scripts in sequential order based on their version numbers. Scripts must be placed in the directory specified by spring.flyway.locations
, typically src/main/resources/db/migration
.
Naming Convention for Scripts
Scripts should follow the pattern: V<version>__<description>.sql
.
Example: V1__Initial_schema.sql
Example: V2__Add_department_table.sql
4. Running Migrations
When the application starts, Flyway automatically applies migration scripts to the database. The migration history is stored in a flyway_schema_history
table.
Flyway CLI (Optional)
You can also run migrations manually using Flyway's command-line interface.
Practical Examples
Example 1: Rolling Back a Migration
Flyway does not support automatic rollback. However, you can create a new script to reverse changes manually.
Rollback Script: V2.1__Rollback_add_department.sql
Example 2: Validating Database Schema
Flyway ensures the database schema matches the migration history. Add this property to enable validation:
Example 3: Using Flyway in Tests
For test environments, Flyway migrations can run using a test-specific configuration.
Test Configuration: application-test.properties
Conclusion
Flyway simplifies database migrations and ensures schema consistency in Spring Boot applications. By following its naming conventions and leveraging its integration with Spring Boot, you can automate version control and schema updates effectively. Proper configuration and script management are key to successful database migrations with Flyway.