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)
相关推荐
Hacker_LaoYi10 分钟前
【渗透技术总结】SQL手工注入总结
数据库·sql
岁月变迁呀12 分钟前
Redis梳理
数据库·redis·缓存
独行soc12 分钟前
#渗透测试#漏洞挖掘#红蓝攻防#护网#sql注入介绍06-基于子查询的SQL注入(Subquery-Based SQL Injection)
数据库·sql·安全·web安全·漏洞挖掘·hw
你的微笑,乱了夏天1 小时前
linux centos 7 安装 mongodb7
数据库·mongodb
黄油饼卷咖喱鸡就味增汤拌孜然羊肉炒饭1 小时前
SpringBoot如何实现缓存预热?
java·spring boot·spring·缓存·程序员
工业甲酰苯胺1 小时前
分布式系统架构:服务容错
数据库·架构
超爱吃士力架1 小时前
邀请逻辑
java·linux·后端
独行soc2 小时前
#渗透测试#漏洞挖掘#红蓝攻防#护网#sql注入介绍08-基于时间延迟的SQL注入(Time-Based SQL Injection)
数据库·sql·安全·渗透测试·漏洞挖掘
White_Mountain2 小时前
在Ubuntu中配置mysql,并允许外部访问数据库
数据库·mysql·ubuntu
Code apprenticeship2 小时前
怎么利用Redis实现延时队列?
数据库·redis·缓存