Flyway 介绍以及与 Spring Boot 集成指南
一、Flyway 简介
Flyway 是一款开源的数据库版本管理工具,通过版本化控制实现数据库结构的自动化升级。其核心特性包括:
支持 SQL 脚本和 Java 迁移代码
提供migrate、clean、validate 等核心命令
自动创建flyway_schema_history 表记录版本变更
使用场景:
比如我们现在有三个环境:开发环境、测试环境、生产环境。
在开发环境建了一张商品表,在开发完毕后,在测试环境和生产环境,我们都需要手动去建同样的商品表
开发时,如果A开发和B开发都对同一数据库进行了修改,那么如何进行数据同步呢?假如多个开发人员都修改了sql脚本,怎么同步到测试环境和生产环境?
二、Spring Boot 集成步骤
1. 添加依赖
在 pom.xml
中添加 Flyway 核心依赖:
<dependency><groupId>org.flywaydb</groupId><artifactId>flyway-core</artifactId><version>7.15.0</version> <!-- 版本根据需求调整 -->
</dependency>
<!-- MySQL 驱动示例 -->
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.26</version>
</dependency>
2. 配置数据库连接
在 application.yml
中添加配置,(flyway里面的数据库指的是目标数据库(如测试环境或生产环境的数据库))
spring:datasource:url: jdbc:mysql://localhost:3306/product_db?useSSL=false&serverTimezone=UTCusername: rootpassword: rootdriver-class-name: com.mysql.cj.jdbc.Driverflyway:# 是否启动flywayenabled: false# 数据库table: flyway_schema_history_check# 编码格式 默认UTF-8encoding: UTF-8# 迁移sql脚本文件存放路径 默认在下面db/migration,可以手动修改locations: classpath:db/migration/mysql# 迁移sql脚本文件名称前缀,默认V 大写sql-migration-prefix: V# 迁移sql脚本文件名称分隔符,默认2个下划线__sql-migration-separator: __# 迁移脚本文件名称后缀sql-migration-suffixes: .sql# 迁移时是否进行校验,默认truevalidate-on-migrate: true# 迁移数据库发现数据库非空且存在没有元数据的表时,自动执行基准迁移,新建schema_version表baseline-on-migrate: true# 禁止清理表数据clean-disabled: true# 多数据源时使用的数据库 连接地址url: ${spring.datasource.dynamic.datasource.primary.url:}# 多数据源时使用的数据库 用户名user: ${spring.datasource.dynamic.datasource.primary.username:}# 多数据源时使用的数据库 密码password: ${spring.datasource.dynamic.datasource.primary.password:}
3. 编写迁移脚本
在迁移脚本的目录下创建 SQL 文件,建议命名:采用 V{版本}__{文件描述}.sql
格式(如 V1_2_0__Add_index.sql)
-- V1__Create_product_table.sql
CREATE TABLE product (id BIGINT PRIMARY KEY AUTO_INCREMENT,name VARCHAR(255) NOT NULL,price DECIMAL(10,2)
);
-- V2__Add_stock_column.sql
ALTER TABLE product ADD COLUMN stock INT DEFAULT 0;
4. 启动项目
项目启动时,flyway会自动执行迁移脚本目录下面的sql文件到指定的数据库信息中,Flyway 还会自动创建一个版本表,用于记录数据库的迁移版本信息。这个表的默认名称是 flyway_schema_history