一、Flyway简介
Flyway 是一款开源的数据库版本管理工具。它可以很方便的在命令行中使用,或者在Java应用程序中引入,用于管理我们的数据库版本。
在项目或产品中,很难一开始就把业务理清楚,把数据库表设计好,因此数据表也会在迭代周期不断迭代。在Java应用程序中使用Flyway,能快速有效地用于迭代数据库表结构,并保证部署到测试环境或生产环境时,数据表都是保持一致的。
Flyway支持的数据库很多,从官网摘抄如下:
Supported databases are Oracle, SQL Server (including Amazon RDS and Azure SQL Database), Azure Synapse (Formerly Data Warehouse), DB2, MySQL (including Amazon RDS, Azure Database & Google Cloud SQL), Aurora MySQL, MariaDB, Percona XtraDB Cluster, TestContainers, PostgreSQL (including Amazon RDS, Azure Database, Google Cloud SQL & Heroku), Aurora PostgreSQL, Redshift, CockroachDB, SAP HANA, Sybase ASE, Informix, H2, HSQLDB, Derby, Snowflake, SQLite and Firebird.
二、Flyway是如何工作的
Flyway工作流程如下:
1、项目启动,应用程序完成数据库连接池的建立后,Flyway自动运行。
2、初次使用时,Flyway会创建一个flyway_schema_history表,用于记录sql执行记录。
3、Flyway会扫描项目指定路径下(默认是classpath:db/migration)的所有sql脚本,与flyway_schema_history表脚本记录进行比对。如果数据库记录执行过的脚本记录,与项目中的sql脚本不一致,Flyway会报错并停止项目执行。
4、如果校验通过,则根据表中的sql记录最大版本号,忽略所有版本号不大于该版本的脚本。再按照版本号从小到大,逐个执行其余脚本。
三、在SpringBoot项目使用Flyway
1、初始化一个SpringBoot项目
引入MySQL数据库驱动依赖等,并且需要引入Flyway依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.3.7.RELEASE</version>
<configuration>
<mainClass>com.example.flyway.FlywayApplication</mainClass>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
2、添加Flyway配置
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/flywaydemo?characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai&useInformationSchema=true
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
flyway:
enabled: true # 开启flyway
# flyway 的 clean 命令会删除指定 schema 下的所有 table, 生产务必禁掉。这个默认值是 false 理论上作为默认配置是不科学的。
clean-disabled: true
locations: classpath:db/migration #flyway文件目录
table: flyway_schema_history #历史表名
baseline-on-migrate: true
validate-on-migrate: true #连续性校验
baseline-version: 1 #指定默认版本
encoding: UTF-8 #编码
out-of-order: false # 是否允许不按顺序迁移 开发建议 true 生产建议 false
sql-migration-prefix: V #前缀默认v
sql-migration-separator: __ #分割符,默认__
sql-migration-suffixes: .sql #迁移文件,默认.sql
springboot在创建项目时导入了flyway,可以不配置yml,采用默认构建
3、构建数据库
SQL语句命名需要遵从一定的规范,否则运行的时候flyway会报错。命名规则主要有两种:
- 仅需要被执行一次的SQL命名以大写的"V"开头,后面跟上"0~9"数字的组合,数字之间可以用“.”或者下划线"_"分割开,然后再以两个下划线分割,其后跟文件名称,最后以.sql结尾。比如,
V2.1.5__create_user_ddl.sql、V4.1_2__add_user_dml.sql。 - 可重复运行的SQL,则以大写的“R”开头,后面再以两个下划线分割,其后跟文件名称,最后以.sql结尾。比如,
R__truncate_user_dml.sql。
其中,V开头的SQL执行优先级要比R开头的SQL优先级高。
数据库名字为 flyway
首次执行需要在数据库实例flyway创建表flyway_schema_history``flyway_schema_history是flyway版本控制记录表,必须要创建。
CREATE TABLE `flyway_schema_history` (
`installed_rank` int(11) NOT NULL,
`version` varchar(50) DEFAULT NULL,
`description` varchar(200) NOT NULL,
`type` varchar(20) NOT NULL,
`script` varchar(1000) NOT NULL,
`checksum` int(11) DEFAULT NULL,
`installed_by` varchar(100) NOT NULL,
`installed_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`execution_time` int(11) NOT NULL,
`success` tinyint(1) NOT NULL,
PRIMARY KEY (`installed_rank`),
KEY `flyway_schema_history_s_idx` (`success`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
接着如下,准备了三个脚本,分别为:
1.V1__create_user.sql,其中代码如下,目的是建立一张user表,且只执行一次。
CREATE TABLE IF NOT EXISTS `USER`(
`USER_ID` INT(11) NOT NULL AUTO_INCREMENT,
`USER_NAME` VARCHAR(100) NOT NULL COMMENT '用户姓名',
`AGE` INT(3) NOT NULL COMMENT '年龄',
`CREATED_TIME` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`CREATED_BY` varchar(100) NOT NULL DEFAULT 'UNKNOWN',
`UPDATED_TIME` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`UPDATED_BY` varchar(100) NOT NULL DEFAULT 'UNKNOWN',
PRIMARY KEY (`USER_ID`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
2.V2__add_user.sql,其中代码如下,目的是往user表中插入一条数据,且只执行一次。
insert into `user`(user_name,age) values('lisi',33);
3.R__add_unknown_user.sql,其中代码如下,目的是每次启动倘若有变化,则往user表中插入一条数据。
insert into `user`(user_name,age) values('unknown',33);
与之相对应的目录截图如下:
注意:这里的文件位置与yaml文件中的路径要对应,否则不能执行sql文件
下图中的文件位置与yaml中的一一对应

或者:

也可以执行指定文件夹中的sql
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/flywaydemo?characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai&useInformationSchema=true
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
flyway:
enabled: true # 开启flyway
# flyway 的 clean 命令会删除指定 schema 下的所有 table, 生产务必禁掉。这个默认值是 false 理论上作为默认配置是不科学的。
clean-disabled: true
locations: classpath:db/migration/create #flyway文件目录
table: flyway_schema_history #历史表名
baseline-on-migrate: true
validate-on-migrate: true #连续性校验
baseline-version: 1 #指定默认版本
encoding: UTF-8 #编码
out-of-order: false # 是否允许不按顺序迁移 开发建议 true 生产建议 false
sql-migration-prefix: V #前缀默认v
sql-migration-separator: __ #分割符,默认__
sql-migration-suffixes: .sql #迁移文件,默认.sql
接下来,数据库中就会有user表了

但是另外两个sql文件并没有执行。
4、启动SpringBoot程序的主程序
到这一步,flyway的默认配置已经足够我们开始运行了。此时,我们启动SpringBoot的主程序,如果以上步骤没有配置错误的话,,启动时会自动执行数据库脚本文件。运行截图如下:
四、flyway注意点
1.flyway执行migrate必须在空白的数据库上进行,否则报错;
2.对于已经有数据的数据库,必须先baseline,然后才能migrate;
3.clean操作是删除数据库的所有内容,包括baseline之前的内容;
4.尽量不要修改已经执行过的SQL,即便是R开头的可反复执行的SQL,它们会不利于数据迁移;
五、flyway的配置清单
flyway.baseline-description对执行迁移时基准版本的描述.
flyway.baseline-on-migrate当迁移时发现目标schema非空,而且带有没有元数据的表时,是否自动执行基准迁移,默认false.
flyway.baseline-version开始执行基准迁移时对现有的schema的版本打标签,默认值为1.
flyway.check-location检查迁移脚本的位置是否存在,默认false.
flyway.clean-on-validation-error当发现校验错误时是否自动调用clean,默认false.
flyway.enabled是否开启flywary,默认true.
flyway.encoding设置迁移时的编码,默认UTF-8.
flyway.ignore-failed-future-migration当读取元数据表时是否忽略错误的迁移,默认false.
flyway.init-sqls当初始化好连接时要执行的SQL.
flyway.locations迁移脚本的位置,默认db/migration.
flyway.out-of-order是否允许无序的迁移,默认false.
flyway.password目标数据库的密码.
flyway.placeholder-prefix设置每个placeholder的前缀,默认${.
flyway.placeholder-replacementplaceholders是否要被替换,默认true.
flyway.placeholder-suffix设置每个placeholder的后缀,默认}.
flyway.placeholders.[placeholder name]设置placeholder的value
flyway.schemas设定需要flywary迁移的schema,大小写敏感,默认为连接默认的schema.
flyway.sql-migration-prefix迁移文件的前缀,默认为V.
flyway.sql-migration-separator迁移脚本的文件名分隔符,默认__
flyway.sql-migration-suffix迁移脚本的后缀,默认为.sql
flyway.tableflyway使用的元数据表名,默认为schema_version
flyway.target迁移时使用的目标版本,默认为latest version
flyway.url迁移时使用的JDBC URL,如果没有指定的话,将使用配置的主数据源
flyway.user迁移数据库的用户名
flyway.validate-on-migrate迁移时是否校验,默认为true
谢谢阅读,无误点赞,有误还望评论区指正。
本文介绍了Flyway作为数据库版本管理工具的原理及在SpringBoot项目中的使用方法,包括初始化项目、添加依赖、配置Flyway、创建数据库脚本以及启动时自动执行的流程。同时,文章提到了Flyway的一些注意事项,如执行前提、数据库清理和脚本修改的潜在问题。
885

被折叠的 条评论
为什么被折叠?



