flyway实现数据库版本控制

什么是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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值