這一段時間項目變動比較大,常常修改表結構,而後各個環境數據庫均爲修改,一不當心就忘掉了,等出問題才發現表結構沒有更新;遂尋找數據庫版本控制工具;最終肯定爲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;">