一般在我们开发项目的时候经常会更新数据库表的字段,如果同事 a 添加了表字段,没有及时给同事 b sql 脚本,
可能同事 b 的代码运行就会报错,而且随着时间的推移,sql 脚本越来越多,项目上线的时候整理起来就很费时间
所以就有大佬级别的人物创造了 Flyway 这个数据库版本管理工具。
GitHub地址:https://github.com/intomylife/SpringBoot
4.0.0
com.zwc
springboot-flyway-commons
0.0.1-SNAPSHOT
springboot-flyway-commons
公用工程
jar
UTF-8
1.8
Cairo-SR3
mysql
mysql-connector-java
org.flywaydb
flyway-core
org.springframework.boot
spring-boot-starter-jdbc
io.spring.platform
platform-bom
${platform-bom.version}
pom
import
org.springframework.boot
spring-boot-maven-plugin
service 工程是一个父工程,里面可能会包含 基础模块,用户模块,订单模块等等... 每个模块中又会分为 core 和 api
# 端口
server.port=8082
# 数据源
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/base_db_test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=PRC&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
# 打印 sql 日志
logging.level.com.zwc.base.mapper=debug
# flyway 注:可以完全不用配置
## sql 脚本的位置,默认为 classpath:db/migration。可手动指定
spring.flyway.locations=classpath:db/zwc
## 指定数据源,如果没有指定的话,将使用配置的主数据源
spring.flyway.url=jdbc:mysql://127.0.0.1:3306/base_db_flyway?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=PRC&useSSL=false
## Flyway 管理的 Schema 列表,区分大小写。默认连接对应的默认 Schema
## 如果这里明确指定了库名,那么在 spring.flyway.url 连接中指定的库名将无效
spring.flyway.schemas=base_db_flyway
## 用户名
spring.flyway.user=root
## 密码
spring.flyway.password=123456
## 开启,默认开启
spring.flyway.enabled=true
a) sql 脚本的位置,默认为 classpath:db/migration。可手动指定
b) 数据源的连接地址,操作的库,用户名以及密码
a) 如果配置了 spring.flyway.schemas 明确指定了库名,那么在 spring.flyway.url 连接中指定的库名将无效
b) spring.flyway.schemas > spring.flyway.url > spring.datasource.url
注:此处为 sql 脚本位置( application.properties -> spring.flyway.locations)
V0.1.0__init_table.sql
-- 创建表
CREATE TABLE `springboot_flyway` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增ID',
`type` varchar(2) DEFAULT NULL COMMENT '生活用品类别:1. 家电类 2. 厨具',
`name` varchar(50) DEFAULT NULL COMMENT '生活用品名称',
`description` varchar(200) DEFAULT NULL COMMENT '生活用品描述',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPACT COMMENT='springboot整合flyway测试表';
V0.1.1__init_data.sql
-- 初始化数据
INSERT INTO springboot_flyway ( type , name , description ) VALUES
('1','电饭煲','用来蒸饭'),('1','电热壶','用来烧水'),('1','空调','用来制冷或制热'),
('2','菜刀','用来切菜'),('2','刨子','用来剥皮'),('2','打蛋器','用来搅拌鸡蛋');
注意命名规范,参考:https://flywaydb.org/documentation/migrations
如果没有翻译全文,搜索关键字 Naming;如果翻译了全文,搜索关键字 命名
注:根据你配置的数据源信息或 Flyway 信息创建好对应的数据库
1. 项目启动成功后,到对应的数据库中刷新,即可看到 Flyway 创建的表
2. 第一次启动的时候,除了主动写的 sql 脚本会被执行以及创建表以外, Flyway 还会自动创建一张历史版本记录的表
到此 SpringBoot 整合 Flyway 就结束了,很简单,主要在配置,多多尝试,一定会成功的!
希望能够帮助到你
over