扫码一下
查看教程更方便
flyway 是一个版本控制应用程序,可在所有实例中轻松可靠地发展数据库模式。 要了解有关 flyway 的更多信息,您可以使用链接 -
许多软件项目使用关系数据库。 这需要处理数据库迁移,通常也称为模式迁移。
在本章中,我们将详细了解如何在 spring boot 应用程序中配置 flyway 数据库。
首先,从 spring initializer 页面 下载 spring boot 项目并选择以下依赖项 -
maven 用户可以在 pom.xml 文件中添加以下依赖项。
org.flywaydb
flyway-core
org.springframework.boot
spring-boot-starter-jdbc
org.springframework.boot
spring-boot-starter-web
mysql
mysql-connector-java
org.springframework.boot
spring-boot-starter-test
test
gradle 用户可以在 build.gradle 文件中添加以下依赖项。
compile('org.flywaydb:flyway-core')
compile('org.springframework.boot:spring-boot-starter-jdbc')
compile('org.springframework.boot:spring-boot-starter-web')
compile('mysql:mysql-connector-java')
在应用程序属性中,我们需要配置用于创建 datasource 的数据库属性以及我们需要在应用程序属性中配置的 flyway 属性。
对于属性文件用户,在 application.properties 文件中添加以下属性。
spring.application.name = flywayapp
spring.datasource.driverclassname = com.mysql.jdbc.driver
spring.datasource.url = jdbc:mysql://localhost:3306/userservice?autoreconnect=true
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.testonborrow = true
spring.datasource.testwhileidle = true
spring.datasource.timebetweenevictionrunsmillis = 60000
spring.datasource.minevictableidletimemillis = 30000
spring.datasource.validationquery = select 1
spring.datasource.max-active = 15
spring.datasource.max-idle = 10
spring.datasource.max-wait = 8000
flyway.url = jdbc:mysql://localhost:3306/mysql
flyway.schemas = userservice
flyway.user = root
flyway.password = root
yaml 用户可以在 application.yml 文件中添加以下属性。
spring:
application:
name: flywayapp
datasource:
driverclassname: com.mysql.jdbc.driver
url: "jdbc:mysql://localhost:3306/userservice?autoreconnect=true"
password: "root"
username: "root"
testonborrow: true
testwhileidle: true
timebetweenevictionrunsmillis: 60000
minevictableidletimemillis: 30000
validationquery: select 1
max-active: 15
max-idle: 10
max-wait: 8000
flyway:
url: jdbc:mysql://localhost:3306/mysql
schemas: userservice
user: "root"
password: "root"
现在,在 src/main/resources/db/migration 目录下创建一个 sql 文件。 将 sql 文件命名为“v1__initial.sql”
create table users (id int auto_increment primary key, userid varchar(45));
insert into users (id, userid) values (1, 'jiyik.com');
下面给出主要的 spring boot 应用程序类文件代码
package com.jiyik.flywayapp;
import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
@springbootapplication
public class flywayappapplication {
public static void main(string[] args) {
springapplication.run(flywayappapplication.class, args);
}
}
现在,我们可以创建一个可执行的 jar 文件,并使用以下 maven 或 gradle 命令运行 spring boot 应用程序。
对于 maven,使用下面给出的命令
$ mvn clean install
成功之后,我们可以在 target 目录下找到 jar 文件。
对于 gradle,使用下面给出的命令
$ gradle clean build
现在,使用以下命令运行 jar 文件
$ java –jar