對於 SpringBoot 專案開發, 其實不需要專門安裝 flyway 命令列工具和 maven 外掛, SpringBoot 啟動就會自動執行 DB migrate 操作。 對於其他的 flyway 操作, 就需要使用命令列工具或 maven 外掛了。
flyway 提供命令列工具, 常用的命令包括:
Clean: 刪除所有建立的資料庫物件, 包括使用者、表、檢視等。 注意不要在生產庫上執行 clean 操作。
Migrate: 對資料庫依次應用版本更改。
Info: 獲取目前資料庫的狀態。 那些遷移已經完成, 那些遷移待完成。 所有遷移的執行時間以及結果。
Validate: 驗證已 Apply 的指令碼是否有變更, Flyway 的 Migration 預設先做 Validate。
Baseline: 根據現有的資料庫結構生成一個基準遷移指令碼。
Repair: 修復命令儘量不要使用, 修復場景有: 1。 移除失敗的 migration 記錄。 2。已經應用的 SQL 指令碼被修改, 我們想重新應用該 SQL 指令碼。
專案結構:
pom。xml新增依賴
maven外掛
application。properties配置
server。port=8081spring。datasource。driver-class-name=com。mysql。cj。jdbc。Driverspring。datasource。url=jdbc:mysql://localhost:3306/flywaytest?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTCspring。datasource。username=rootspring。datasource。password=rootspring。datasource。max-idle=10spring。datasource。max-wait=10000spring。datasource。min-idle=5spring。datasource。initial-size=5mybatis。type-aliases-package=com。example。domainmybatis。mapper-locations=mapper/*。xml# 指定flyway指令碼位置spring。flyway。locations=classpath:/db/migration# 開啟flyway執行日誌logging。level。org。flywaydb=info
測試sql
CREATE TABLE person ( id int(11) NOT NULL AUTO_INCREMENT, first varchar(100) NOT NULL, last varchar(100) NOT NULL, dateofbirth DATE DEFAULT null, placeofbirth varchar(100) not null, PRIMARY KEY (id)) ENGINE=InnoDB DEFAULT CHARSET=utf8;
啟動專案
資料庫會多出以下這張表,來記錄執行的操作!
sql已執行成功! 注意執行後的sql指令碼不要進行修改,否則會報錯!
可能遇到的問題:
問題1:
Caused by: java。lang。NoClassDefFoundError: org/flywaydb/core/api/configuration/FluentConfiguration
修改flyway-core版本即可!
問題2:
V1__init_database。sql執行後,再次改動V1__init_database。sql,啟動會報錯!
org。springframework。beans。factory。BeanCreationException: Error creating bean with name ‘flywayInitializer’ defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration。class]: Invocation of init method failed; nested exception is org。flywaydb。core。api。FlywayException: Validate failed: Migration checksum mismatch for migration version 1
-> Applied to database : 135091410
-> Resolved locally : -724292036
Caused by: org。flywaydb。core。api。FlywayException: Validate failed: Migration description mismatch for migration version 1
那麼出現這個問題的原因是什麼呢?
這裡涉及到flyway的一些基本常識,flyway 官方文件:https://flywaydb。org/documentation/
常識1):專案每次執行,都會呼叫資料庫,會先執行SQL Script 要使用到Flyway,但是flyway查詢資料時,會判斷資料庫的資料結構或者資料什麼的是否改變,判斷標準就是checksum。
問題3:
如果資料庫存在表,並且sql指令碼之前沒有被執行過,啟動程式會報錯;
大家可以關注我一起學習!個人能力有限,有問題可以提出,大家共同進步!謝謝!