什么是flyway
简单地说,flyway是一个能对数据库变更做版本控制的工具。flyway官网
为什么用flyway
数据库的变更(table增删改等等)需要版本控制。在日常开发中,我们经常会遇到下面的问题:
- 不知道前人对数据库做过哪些修改
- 同一句DDL不能确定是否都在所有环境执行过了
- 数据库迁移需要重新建表
有了flyway,这些问题都能得到很好的解决
如何使用flyway
引入依赖
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
<version>8.5.13</version>
</dependency>
在工程项目中准备好DDL文件,以0001__xxxxx命名
在代码中调用flyway
LOG.info("rollback={}, flyway migration location={}", IS_ROLLBACK, MIGRATION_LOCATION);
Flyway flyway = Flyway.configure()
.locations(MIGRATION_LOCATION)
.dataSource(DB_URL, USER, PASS)
.validateOnMigrate(false)
.baselineOnMigrate(true)
.sqlMigrationPrefix("0")
.load();
flyway.migrate();
执行代码会看到类似如下的日志,说明flyway已经执行了你的DDL
[main] INFO org.flywaydb.core.internal.license.VersionPrinter - Flyway Community Edition 8.5.13 by Redgate
[main] INFO org.flywaydb.core.internal.license.VersionPrinter - See what's new here: https://flywaydb.org/documentation/learnmore/releaseNotes#8.5.13
[main] INFO org.flywaydb.core.internal.license.VersionPrinter -
[main] INFO org.flywaydb.core.internal.database.base.BaseDatabaseType - Database: jdbc:h2:~/test (H2 2.1)
[main] INFO org.flywaydb.core.internal.schemahistory.JdbcTableSchemaHistory - Creating Schema History table "PUBLIC"."flyway_schema_history" ...
[main] INFO org.flywaydb.core.internal.command.DbMigrate - Current version of schema "PUBLIC": << Empty Schema >>
[main] INFO org.flywaydb.core.internal.command.DbMigrate - Migrating schema "PUBLIC" to version "001 - create tutorials"
[main] INFO org.flywaydb.core.internal.command.DbMigrate - Migrating schema "PUBLIC" to version "002 - alter tutorials"
[main] INFO org.flywaydb.core.internal.command.DbMigrate - Successfully applied 2 migrations to schema "PUBLIC", now at version v002 (execution time 00:00.040s)
查看目标数据库,发现flyway会自动生成一个flyway_schema_history的表,用于记录flyway做的数据库变更,也就是版本控制
Demo代码已经上传github: GitHub - bin9wei/flyway-db-maintainer: Java application to do database schema change with flyway