首先介绍一些什么是flyway以及为什么要使用它
Flyway是独立于数据库的应用、管理并跟踪数据库变更的数据库版本管理工具。用通俗的话讲,Flyway可以像Git管理不同人的代码那样,管理不同人的sql脚本,从而做到数据库同步。
使用flyway可以自动执行系统的sql脚本文件,这为我们省去了很多时间
下面说一下集成步骤:
第一步:引入jar包
<dependency> <groupId>org.flywaydb</groupId> <artifactId>flyway-core</artifactId> <version>7.9.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.49</version> <scope>runtime</scope> </dependency>
若要使用flyway的插件,则引入下面的插件
<plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.flywaydb</groupId> <artifactId>flyway-maven-plugin</artifactId> <configuration> <driver>com.mysql.jdbc.Driver</driver> <url>jdbc:mysql://localhost:3306/study?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false</url><!--&是&的转义字符--> <user>root</user> <password>12345678</password> <!--<schemas></schemas>--> </configuration> </plugin> </plugins>
注意:因为flyway是基于数据库管理,所以必须引入数据库驱动文件及数据库配置
第二步:配置yml文件
spring: datasource: url: jdbc:mysql://localhost:3306/study?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false username: root password: 12345678 driver-class-name: com.mysql.jdbc.Driver flyway: enabled: false encoding: UTF-8 url: jdbc:mysql://localhost:3306/study?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false user: root password: 12345678 locations: classpath:db/migration sql-migration-prefix: v sql-migration-separator: _ # init-sqls: select * from person
这里需要注意的是locations的位置及sql-migration-prefix(默认为V)和 sql-migration-separato(默认为__)的配置.
至此,flyway的集成就算完成了,项目启动的时候会去找locations: classpath:db/migration下面的vxxx_xxx.sql文件自动执行。