Spring Boot Flyway資料庫


Flyway是一個版本控制應用程式,可以在所有範例中輕鬆可靠地演變資料庫模式。 要了解有關Flyway的更多資訊,可以使用連結 - www.flywaydb.org

許多軟體專案使用關聯式資料庫。 這需要處理資料庫遷移,通常也稱為模式遷移
在本章中,將詳細了解如何在Spring Boot應用程式中組態Flyway資料庫。

組態Flyway資料庫

首先,從Spring Initializer 頁面 www.start.spring.io 下載Spring Boot專案並選擇以下依賴項 -

  • Spring Boot Starter Web
  • Flyway
  • MySQL
  • JDBC

Maven使用者可以在pom.xml 檔案中新增以下依賴項。

<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>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
</dependency>

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
</dependency>

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, 'tw511.com');

主 Spring Boot應用程式類檔案程式碼如下 -

package com.yiibai.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);
   }
}

完整的構建組態檔案如下所示。

Maven構建檔案 - pom.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">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.yiibai</groupId>
   <artifactId>flywayapp</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>flywayapp</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.9.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <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>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>

      <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>

Gradle構建檔案 – build.gradle

buildscript {
   ext {
      springBootVersion = '1.5.9.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.yiibai'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
dependencies {
   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')
   testCompile('org.springframework.boot:spring-boot-starter-test')
}

可以建立一個可執行的JAR檔案,並使用下面給出的Maven或Gradle命令執行Spring Boot應用程式 -

對於Maven,可以使用此處顯示的命令 -

mvn clean install

在「BUILD SUCCESS」之後,可以在target目錄下找到JAR檔案。

對於Gradle,可以使用此處顯示的命令 -

gradle clean build

在「BUILD SUCCESSFUL」之後,可以在build libs 目錄下找到JAR檔案。

現在,使用以下命令執行JAR檔案 -

java –jar <JARFILE>

現在,Tomcat在埠8080上啟動,在控制台視窗中,可以看到如此處所示的flyway資料庫紀錄檔。

pringframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-10-08 21:07:58.525  INFO 16088 --- [           main] o.f.core.internal.util.VersionPrinter    : Flyway 3.2.1 by Boxfuse
Mon Oct 08 21:07:58 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Mon Oct 08 21:07:58 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
2018-10-08 21:07:58.825  INFO 16088 --- [           main] o.f.c.i.dbsupport.DbSupportFactory       : Database: jdbc:mysql://localhost:3306/mysql (MySQL 5.7)
2018-10-08 21:07:58.860  INFO 16088 --- [           main] o.f.core.internal.command.DbValidate     : Validated 1 migration (execution time 00:00.014s)
2018-10-08 21:07:59.150  INFO 16088 --- [           main] o.f.c.i.metadatatable.MetaDataTableImpl  : Creating Metadata table: `testdb`.`schema_version`
2018-10-08 21:07:59.987  INFO 16088 --- [           main] o.f.core.internal.command.DbMigrate      : Current version of schema `testdb`: << Empty Schema >>
2018-10-08 21:07:59.988  INFO 16088 --- [           main] o.f.core.internal.command.DbMigrate      : Migrating schema `testdb` to version 1 - Initial
2018-10-08 21:08:00.092  INFO 16088 --- [           main] o.f.core.internal.command.DbMigrate      : Successfully applied 1 migration to schema `testdb` (execution time 00:00.947s).
2018-10-08 21:08:00.339  INFO 16088 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-10-08 21:08:00.515  INFO 16088 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2018-10-08 21:08:00.526  INFO 16088 --- [           main] c.yiibai.flywayapp.FlywayappApplication  : Started FlywayappApplication in 6.384 seconds (JVM running for 6.903)
2018-10-08 21:08:20.802  INFO 16088 --- [       Thread-3] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot[email protected]14514713: startup date [Mon Oct 08 21:07:54 CST 2018]; root of context hierarchy
2018-10-08 21:08:20.810  INFO 16088 --- [       Thread-3] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown

現在連線到資料庫並執行選擇查詢。結果如下所示 -