SpringBoot集成数据库界的版本控制工具flyway

Flyway 就是一款数据库界的版本控制工具,它可以记录数据库的变化记录。统一管理所有的 SQL 脚本变更,在所有环境自动同步数据库,而无需人为手工控制,再也不用担心因数据库不同步而导致的各种环境问题。

MySQL环境准备

yml 复制代码
version: '3'
services:
  mysql:
    image: registry.cn-hangzhou.aliyuncs.com/zhengqing/mysql:5.7  # 原镜像`mysql:5.7`
    container_name: mysql_3306                                    # 容器名为'mysql_3306'
    restart: unless-stopped                                       # 指定容器退出后的重启策略为始终重启,但是不考虑在Docker守护进程启动时就已经停止了的容器
    volumes:                                                      # 数据卷挂载路径设置,将本机目录映射到容器目录
      - "./mysql/my.cnf:/etc/mysql/my.cnf"
      - "./mysql/init-file.sql:/etc/mysql/init-file.sql"
      - "./mysql/data:/var/lib/mysql"
#      - "./mysql/conf.d:/etc/mysql/conf.d"
      - "./mysql/log/mysql/error.log:/var/log/mysql/error.log"
      - "./mysql/docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d" # 可执行初始化sql脚本的目录 -- tips:`/var/lib/mysql`目录下无数据的时候才会执行(即第一次启动的时候才会执行)
    environment:                        # 设置环境变量,相当于docker run命令中的-e
      TZ: Asia/Shanghai
      LANG: en_US.UTF-8
      MYSQL_ROOT_PASSWORD: root         # 设置root用户密码
      MYSQL_DATABASE: demo              # 初始化的数据库名称
    ports:                              # 映射端口
      - "3306:3306"

启动:docker-compose -f docker-compose.yml -p mysql5.7 up -d

一、依赖

xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springboot-demo</artifactId>
        <groupId>com.et</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>flyway</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- flyway-core 依赖 V:7.7.3 -->
        <dependency>
            <groupId>org.flywaydb</groupId>
            <artifactId>flyway-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

    </dependencies>
</project>

二、配置文件和启动类

application.yaml

yaml 复制代码
server:
  port: 8088
spring:
  # flyway 配置
  flyway:
    # 开启 flyway
    enabled: true
    # 是否禁用数据库清理
    clean-disabled: true
    # SQL 迁移的编码
    encoding: UTF-8
    # 迁移脚本的位置,默认 db/migration.
    locations: classpath:db/migration
    # SQL 迁移的文件名前缀。
    sql-migration-prefix: V
    # SQL 迁移的文件名分隔符。
    sql-migration-separator: __
    # SQL 迁移的文件名后缀。
    sql-migration-suffixes: .sql
    # 是否在执行迁移时自动调用验证。
    validate-on-migrate: true
    # 迁移时发现目标 schema 非空,而且带有没有元数据的表时,是否自动执行基准迁移,默认 false.
    baseline-on-migrate: true
    # JDBC 驱动程序的完全限定名称。 默认根据 URL 自动检测。
    driver-class-name:
    # 要迁移的数据库的 DBC url。 如果未设置,则使用主要配置的数据源。
    url: jdbc:mysql://localhost:3306/zq?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
    # 要迁移的数据库的登录密码。
    password: root
    # 要迁移的数据库的登录用户。
    user: root

  # MySQL 配置
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/zq
    username: root
    password: root

三、测试

测试一: 创建表 sql文件,在resource文件下面,创建db/migration,

V1__user_version.sql

sql 复制代码
DROP TABLE IF EXISTS user ;
CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `name` varchar(20) NOT NULL COMMENT '姓名',
  `age` int(5) DEFAULT NULL COMMENT '年龄',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

启动springboot应用

bash 复制代码
2024-03-05 10:27:54.267 INFO 20728 --- [ main] o.f.c.internal.license.VersionPrinter : Flyway Community Edition 6.0.8 by Redgate
2024-03-05 10:27:54.862 INFO 20728 --- [ main] o.f.c.internal.database.DatabaseFactory : Database: jdbc:mysql://localhost:3306/zq (MySQL 5.7)
2024-03-05 10:27:54.901 INFO 20728 --- [ main] o.f.core.internal.command.DbValidate : Successfully validated 1 migration (execution time 00:00.015s)
2024-03-05 10:27:55.051 INFO 20728 --- [ main] o.f.c.i.s.JdbcTableSchemaHistory : Creating Schema History table `zq`.`flyway_schema_history` ...
2024-03-05 10:27:55.151 INFO 20728 --- [ main] o.f.core.internal.command.DbMigrate : Current version of schema `zq`: << Empty Schema >>
2024-03-05 10:27:55.159 INFO 20728 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema `zq` to version 1 - user version
2024-03-05 10:27:55.166 WARN 20728 --- [ main] o.f.c.i.s.DefaultSqlScriptExecutor : DB: Unknown table 'zq.user' (SQL State: 42S02 - Error Code: 1051)
2024-03-05 10:27:55.217 INFO 20728 --- [ main] o.f.core.internal.command.DbMigrate : Successfully applied 1 migration to schema `zq` (execution time 00:00.075s)
2024-03-05 10:27:55.290 INFO 20728 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8088 (http) with context path ''
2024-03-05 10:27:55.293 INFO 20728 --- [ main] com.et.flyway.DemoApplication : Started DemoApplication in 2.896 seconds (JVM running for 3.283)

sql更新

V1_1__alter_table_user.sql

sql 复制代码
ALTER TABLE `user` ADD COLUMN `address` VARCHAR(20) DEFAULT NULL;

启动应用spring boot应用,第二次并不会执行2个脚本,它会从上次的版本号开始往后执行。如下图所示

bash 复制代码
2024-03-05 10:31:22.738 INFO 29244 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2024-03-05 10:31:22.931 INFO 29244 --- [ main] o.f.c.internal.license.VersionPrinter : Flyway Community Edition 6.0.8 by Redgate
2024-03-05 10:31:23.479 INFO 29244 --- [ main] o.f.c.internal.database.DatabaseFactory : Database: jdbc:mysql://localhost:3306/zq (MySQL 5.7)
2024-03-05 10:31:23.522 INFO 29244 --- [ main] o.f.core.internal.command.DbValidate : Successfully validated 2 migrations (execution time 00:00.022s)
2024-03-05 10:31:23.537 INFO 29244 --- [ main] o.f.core.internal.command.DbMigrate : Current version of schema `zq`: 1
2024-03-05 10:31:23.547 INFO 29244 --- [ main] o.f.core.internal.command.DbMigrate : Migrating schema `zq` to version 1.1 - alter table user
2024-03-05 10:31:23.617 INFO 29244 --- [ main] o.f.core.internal.command.DbMigrate : Successfully applied 1 migration to schema `zq` (execution time 00:00.089s)
2024-03-05 10:31:23.684 INFO 29244 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8088 (http) with context path ''
2024-03-05 10:31:23.687 INFO 29244 --- [ main] com.et.flyway.DemoApplication : Started DemoApplication in 2.702 seconds (JVM running for 3.027)
相关推荐
计算机-秋大田2 分钟前
基于Spring Boot的船舶监造系统的设计与实现,LW+源码+讲解
java·论文阅读·spring boot·后端·vue
Dxy123931021610 分钟前
python下载pdf
数据库·python·pdf
桀桀桀桀桀桀1 小时前
数据库中的用户管理和权限管理
数据库·mysql
代码之光_19801 小时前
保障性住房管理:SpringBoot技术优势分析
java·spring boot·后端
ajsbxi1 小时前
苍穹外卖学习记录
java·笔记·后端·学习·nginx·spring·servlet
superman超哥2 小时前
04 深入 Oracle 并发世界:MVCC、锁、闩锁、事务隔离与并发性能优化的探索
数据库·oracle·性能优化·dba
用户8007165452002 小时前
HTAP数据库国产化改造技术可行性方案分析
数据库
颜淡慕潇2 小时前
【K8S问题系列 |1 】Kubernetes 中 NodePort 类型的 Service 无法访问【已解决】
后端·云原生·容器·kubernetes·问题解决
戴眼镜的猴2 小时前
Spring Boot的过滤器与拦截器的区别
spring boot