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)
相关推荐
尘浮生13 分钟前
Java项目实战II基于微信小程序的电影院买票选座系统(开发文档+数据库+源码)
java·开发语言·数据库·微信小程序·小程序·maven·intellij-idea
六月闻君27 分钟前
MySQL 报错:1137 - Can‘t reopen table
数据库·mysql
SelectDB技术团队35 分钟前
兼顾高性能与低成本,浅析 Apache Doris 异步物化视图原理及典型场景
大数据·数据库·数据仓库·数据分析·doris
郑祎亦36 分钟前
Spring Boot 项目 myblog 整理
spring boot·后端·java-ee·maven·mybatis
本当迷ya1 小时前
💖2025年不会Stream流被同事排挤了┭┮﹏┭┮(强烈建议实操)
后端·程序员
inventecsh1 小时前
mongodb基础操作
数据库·mongodb
白云如幻1 小时前
SQL99版链接查询语法
数据库·sql·mysql
爱吃烤鸡翅的酸菜鱼1 小时前
MySQL初学之旅(4)表的设计
数据库·sql·mysql·database
计算机毕设指导62 小时前
基于 SpringBoot 的作业管理系统【附源码】
java·vue.js·spring boot·后端·mysql·spring·intellij-idea
paopaokaka_luck2 小时前
[371]基于springboot的高校实习管理系统
java·spring boot·后端