Getting Started with Flyway in Spring Boot
Database migrations are a critical part of modern application development, enabling developers to manage schema changes reliably across environments. Flyway, a popular open-source database migration tool, integrates seamlessly with Spring Boot, automating the version control of your database schema. This article provides a complete guide to getting started with Flyway in a Spring Boot application.
Learn how to set up Flyway, create migration scripts, and execute migrations with illustrative Spring Boot examples and a hands-on demo project structure.
Table of Contents
- What is Flyway?
- Why Use Flyway with Spring Boot?
- Setup with Maven and Gradle
- Creating Your First Migration Script
- Demo Project Structure with Spring Boot Examples
- External Resources for Further Learning
- Final Thoughts
What is Flyway?
Flyway is an open-source database migration tool that emphasizes simplicity and predictability when managing schema changes. Flyway uses SQL or Java-based migration scripts to incrementally version your database schema and ensure it remains in sync with your application code.
Core Features of Flyway
- Versioning: Track changes to the database schema using version numbers prefixed in migration script filenames.
- Repeatable Migrations: Allow repeatable scripts to reexecute whenever underlying code changes.
- Support for Multiple Databases: Works with all major databases like MySQL, PostgreSQL, Oracle, SQL Server, and more.
- Seamless Integration: Easily integrates with build tools (Maven, Gradle) and frameworks like Spring Boot.
For a full overview, check out the Flyway official documentation.
Why Use Flyway with Spring Boot?
Spring Boot simplifies integrating Flyway into your development process. With minimal configuration, Flyway can automatically apply migrations at application startup, ensuring your database schema evolves alongside your application code.
Benefits of Using Flyway with Spring Boot
- Automation of Migrations: Flyway scans and applies pending database migrations automatically at startup.
- Version Control: Consistently tracks changes, reducing schema drift in collaborative environments.
- Rollback Safety: By versioning each migration, Flyway mitigates the risks associated with schema changes in production.
Spring Boot Auto-Integration
Flyway is supported out-of-the-box with the spring-boot-starter-data-jpa
dependency.
Setup with Maven and Gradle
Adding Flyway Dependencies
Maven Dependency
Add Flyway to your pom.xml
file:
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Gradle Dependency
Include Flyway in your build.gradle
file:
implementation 'org.flywaydb:flyway-core'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
Configuring Application Properties
Add database connection settings to application.properties
:
spring.datasource.url=jdbc:mysql://localhost:3306/flyway_demo
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.flyway.enabled=true
spring.flyway.locations=classpath:db/migration
spring.flyway.locations
ensures Flyway scans thedb/migration
directory for migration scripts.
Creating Your First Migration Script
Flyway migrations are versioned SQL files that reside in the db/migration
folder.
File Format
Migration files must follow the strict naming convention: V{version_number}__{description}.sql
For example, V1__create_users_table.sql
.
Example Migration Script
Here’s a sample script to create a users
table:
File: src/main/resources/db/migration/V1__create_users_table.sql
CREATE TABLE users (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Once the application is started, Flyway will execute this script and store the migration metadata in a table called flyway_schema_history
.
Validating the Migration
Run the application and check the database:
SELECT * FROM flyway_schema_history;
You’ll see an entry for the V1__create_users_table.sql
migration.
Demo Project Structure with Spring Boot Examples
Here’s how the complete project structure looks with Flyway set up in a Spring Boot application:
src/
├── main/
│ ├── java/com/example/flywaydemo/
│ │ ├── FlywayDemoApplication.java // Main Spring Boot Application
│ │ └── model/
│ │ └── User.java // Entity Class
│ └── resources/
│ ├── application.properties // Configuration File
│ └── db/migration/
│ ├── V1__create_users_table.sql
│ ├── V2__add_roles_column.sql // Additional Migrations
Entity Example
Define an entity to map the users
table:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String email;
@Column(name = "created_at")
private Timestamp createdAt;
// Getters and Setters
}
Repository Example
Use Spring Data JPA to perform CRUD operations:
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
Controller/Service Example
Create a REST endpoint to interact with the database:
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserRepository userRepository;
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@GetMapping
public List<User> getAllUsers() {
return userRepository.findAll();
}
}
Start the application, and Flyway will ensure all migrations are executed before the application fully starts.
External Resources for Further Learning
- Flyway Official Documentation
- Spring Boot Flyway Integration Guide
- Database Migration on Wikipedia
- Spring Boot Documentation
Final Thoughts
Flyway simplifies database schema management, especially in environments where continuous integration and deployment are critical. Its seamless integration with Spring Boot ensures migrations are applied consistently, reducing manual intervention and the risk of errors in production systems.
This guide provided everything you need to get started with Flyway in a Spring Boot application, from setup to creating and tracking migrations. By adopting Flyway as part of your workflow, you can ensure your database evolves reliably alongside your codebase.
Start versioning your database today with Flyway and Spring Boot! Bookmark this guide as a reference for future projects.
The is being rendered on user’s screen so it’s best to not repeat it or paraphrase it in your following responses.
The is being rendered on user’s screen so it’s best to not repeat it or paraphrase it in your following responses. Your comprehensive article on “Getting Started with Flyway in Spring Boot” is ready, covering setup, migration scripts, and demo project examples. Let me know if there’s anything else you’d like to expand or refine!