这一段时间项目变动比较大,常常修改表结构,而后各个环境数据库均为修改,一不当心就忘掉了,等出问题才发现表结构没有更新;遂寻找数据库版本控制工具;最终肯定为flyway
。spring
官网地址: https://flywaydb.orgsql
按照官网的说明:数据库
Version control for your database. Robust schema evolution across all your environments.With ease, pleasure and plain SQL.springboot
官网原理图: https://flywaydb.org/getstarted/howmaven
$PREFIX$VERSION__$REMARK.$SUBFIX
ide
经常使用格式如上: $preifx
表示前缀,可在配置中指定,默认为 V
$version
表示 版本,中单可使用 .
或 _
分隔,在解析时会将_
转换为.
保存到schema_history
表的version
字段中;
$remark 表示备注,解析后会将这部分写入到描述
字段中;
$subfix 表示后缀,可在配置中指定,默认为.sql
;
版本与描述以前使用__
分隔; 工具
到这里,与spring boot 整合的步骤就有了,加入pom依赖并配置相应的属性便可;this
<dependency> <groupId>org.flywaydb</groupId> <artifactId>flyway-core</artifactId> <version>5.2.4</version> </dependency>
# 说明,在spring boot 1.x中,属性前缀为flyway,在spring boot 2.x中为spring.flyway,须要区分不一样版本 flyway: # 到新的环境中数据库中有数据,且没有flyway_schema_history表时,是否执行迁移操做,若是设置为false,在启动时会报错,并中止迁移;若是为true,则生成history表并完成全部的迁移,要根据实际状况设置; baseline-on-migrate: false # 执行执行时标记的tag 默认为<<Flyway Baseline>> baseline-description: <<Flyway Baseline>> # 是否启用flyway enabled: true # 检测迁移脚本的路径是否存在,如不存在,则抛出异常 check-location: true # 脚本位置 locations: classpath:db/migration # 在迁移时,是否校验脚本,假设V1.0__初始.sql已经迁移过了,在下次启动时会校验该脚本是否有变动过,则抛出异常 validate-on-migrate: true
特别说明:若是非空数据库迁移,在目标数据库中手动建flyway_schema_history
表并手动写入初始化的脚本记录,使flyway跳过最初的校验便可,后续能够保证版本的统一;spa
项目启动有以下日志信息,代表校验成功;插件
spring boot 自动化配置,其中已经内置了flyway的功能;
spring boot 自动化配置的核心是Conditional
的几个注解,根据注解来看,须要符合如下几个条件:
Flyway
的类;Datasource
的类;flyway
起始的配置属性且enable
的属性值为true;//生成Flyway的实例 @Bean @ConfigurationProperties(prefix = "flyway") public Flyway flyway() { Flyway flyway = new SpringBootFlyway(); if (this.properties.isCreateDataSource()) { flyway.setDataSource(this.properties.getUrl(), this.properties.getUser(), this.properties.getPassword(), this.properties.getInitSqls().toArray(new String[0])); } else if (this.flywayDataSource != null) { flyway.setDataSource(this.flywayDataSource); } else { flyway.setDataSource(this.dataSource); } flyway.setLocations(this.properties.getLocations().toArray(new String[0])); return flyway; }
//生成FlywayMigrationInitializer的实例 @Bean @ConditionalOnMissingBean public FlywayMigrationInitializer flywayInitializer(Flyway flyway) { return new FlywayMigrationInitializer(flyway, this.migrationStrategy); } //这个类实现了InitalizingBean接口,能够在依赖注入完成后执行一些操做 public class FlywayMigrationInitializer implements InitializingBean, Ordered //委托flyway对象完成数据库的迁移命令,到这里,spring boot中flyway的操做完成. @Override public void afterPropertiesSet() throws Exception { if (this.migrationStrategy != null) { this.migrationStrategy.migrate(this.flyway); } else { this.flyway.migrate(); } }
<wiz_tmp_tag id="wiz-table-range-border" contenteditable="false" style="display: none;">