1、创建springboot工程,使用的版本为2.4
工程结构如下:
2、增加依赖
<!--flywaydb--> <dependency> <groupId>org.flywaydb</groupId> <artifactId>flyway-core</artifactId> <version>5.2.1</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
3、application.yml 配置
创建空的数据库flyway
spring: datasource: url: jdbc:mysql://localhost:3306/flyway?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT username: root password: 123456 driver: com.mysql.cj.jdbc.Driver #flyway配置 flyway: baseline-on-migrate: true #数据库连接配置 url: jdbc:mysql://localhost:3306/flyway?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT user: root password: 123456 #忽略脚本顺序 out-of-order: true
4、在resources文件夹下创建db/migration 文件夹
SQL文件的命名需要遵从一定的规范,否则运行的时候会报错。
1、仅需要执行一次的SQL: V开头,后面跟上数字,数字之间可以是"."或者“_"分开。然后再以两个下划线分割。
2、可重复运行的SQL,以”R“开头,后面再跟两个下划线。
V1.1__create_user_ddl.sql
CREATE TABLE IF NOT EXISTS `USER`( `USER_ID` INT(11) NOT NULL AUTO_INCREMENT, `USER_NAME` VARCHAR(100) NOT NULL COMMENT '用户姓名', `AGE` INT(3) NOT NULL COMMENT '年龄', `CREATED_TIME` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `CREATED_BY` varchar(100) NOT NULL DEFAULT 'UNKNOWN', `UPDATED_TIME` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `UPDATED_BY` varchar(100) NOT NULL DEFAULT 'UNKNOWN', PRIMARY KEY (`USER_ID`) )ENGINE=InnoDB DEFAULT CHARSET=utf8;
V1.2__add_user_dml.sql
insert into `user`(user_name,age) values('lisi',33);
R__add_unknown_user.sql.sql
insert into `user`(user_name,age) values('unknown',33);
5、启动程序
查看数据库,创建了两张条,分别为flyway_schema_history和user
flyway_schema_history表
user表
6、插件的使用
<plugin> <groupId>org.flywaydb</groupId> <artifactId>flyway-maven-plugin</artifactId> <version>5.2.1</version> <configuration> <url>jdbc:mysql://localhost:3306/flyway?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT</url> <user>root</user> <password>root</password> <driver>com.mysql.cj.jdbc.Driver</driver> </configuration> </plugin>