一起來學SpringBoot | 第二十四篇:數據庫管理與遷移(Liquibase)

SpringBoot 是爲了簡化 Spring 應用的創建、運行、調試、部署等一系列問題而誕生的產物,自動裝配的特性讓我們可以更好的關注業務本身而不是外部的XML配置,我們只需遵循規範,引入相關的依賴就可以輕易的搭建出一個 WEB 工程

目前 Spring Boot 支持較好的兩款工具分別是 flywayliquibase,支持 sql script,在初始化數據源之後執行指定的腳本代碼或者腳本文件,本章基於 Liquibase

Liquibase

LiquiBase 是一個用於數據庫重構和遷移的開源工具,通過 changelog文件 的形式記錄數據庫的變更,然後執行 changelog文件 中的修改,將數據庫更新或回滾到一致的狀態。

主要特點

  • 支持幾乎所有主流的數據庫,如MySQL、PostgreSQL、Oracle、Sql Server、DB2等
  • 支持多開發者的協作維護;
  • 日誌文件支持多種格式;如XML、YAML、SON、SQL等
  • 支持多種運行方式;如命令行、Spring 集成、Maven 插件、Gradle 插件等

在平時開發中,無可避免測試庫增加字段或者修改字段以及創建表之類的,環境切換的時候如果忘記修改數據庫那麼肯定會出現 不可描述的事情 ,這個時候不妨考慮考慮Liquibase

官方文檔:http://www.liquibase.org/documentation/index.html

本章目標

利用 Spring Boot 集成 Liquibase,避免因粗心大意導致環境遷移時缺少字段….

導入依賴

依賴 spring-boot-starter-jdbc 目的是爲了讓 liquibase 能夠獲得 datasource ,這裏換成 mybatishibernate 等也是一樣,主要偷懶不想寫配置….

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>org.liquibase</groupId>
        <artifactId>liquibase-core</artifactId>
    </dependency>
</dependencies>

屬性配置

只要依賴了 liquibase-core 默認可以不用做任何配置,但還是需要知道默認配置值是什麼,這樣方便定位和解決問題

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/chapter23?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
# 只要依賴了 liquibase-core 默認可以不用做任何配置,但還是需要知道默認配置值是什麼
# spring.liquibase.enabled=true
# spring.liquibase.change-log=classpath:/db/changelog/db.changelog-master.yaml

更多配置

  • spring.liquibase.change-log 配置文件的路徑,默認值爲 classpath:/db/changelog/db.changelog-master.yaml
  • spring.liquibase.check-change-log-location 檢查 change log的位置是否存在,默認爲true.
  • spring.liquibase.contexts 用逗號分隔的運行環境列表。
  • spring.liquibase.default-schema 默認數據庫 schema
  • spring.liquibase.drop-first 是否先 drop schema(默認 false
  • spring.liquibase.enabled 是否開啓 liquibase(默認爲 true
  • spring.liquibase.password 數據庫密碼
  • spring.liquibase.url 要遷移的JDBC URL,如果沒有指定的話,將使用配置的主數據源.
  • spring.liquibase.user 數據用戶名
  • spring.liquibase.rollback-file 執行更新時寫入回滾的 SQL文件

db.changelog-master.yaml

databaseChangeLog:
  # 支持 yaml 格式的 SQL 語法
  - changeSet:
      id: 1
      author: Levin
      changes:
        - createTable:
            tableName: person
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: first_name
                  type: varchar(255)
                  constraints:
                    nullable: false
              - column:
                  name: last_name
                  type: varchar(255)
                  constraints:
                    nullable: false

  - changeSet:
      id: 2
      author: Levin
      changes:
        - insert:
            tableName: person
            columns:
              - column:
                  name: first_name
                  value: Marcel
              - column:
                  name: last_name
                  value: Overdijk
  # 同時也支持依賴外部SQL文件(TODO 個人比較喜歡這種)
  - changeSet:
      id: 3
      author: Levin
      changes:
        - sqlFile:
            encoding: utf8
            path: classpath:db/changelog/sqlfile/test1.sql

test1.sql

INSERT INTO `person` (`id`, `first_name`, `last_name`) VALUES ('2', '哈哈', '呵呵');

上面的yaml文件其實就是從下面的 XML 演變而來的,官方是支持 xmlyamljson 三種格式,寫法也比較簡單

傳送門(官方給出了三種寫法格式,依樣畫葫蘆就可以了):http://www.liquibase.org/documentation/changes/sql_file.html

<?xml version="1.0" encoding="UTF-8" standalone="no"?>  
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"   
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd">  
    <changeSet id="1" author="Levin">
        <sqlFile path="classpath:db/changelog/changelog/test1.sql"/>
    </changeSet>
</databaseChangeLog>  

主函數

package com.battcn;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


/**
 * @author Levin
 */
@SpringBootApplication
public class Chapter23Application {

    public static void main(String[] args) {

        SpringApplication.run(Chapter23Application.class, args);

    }
}

測試

1.啓動Chapter23Application.java中的main方法

Liquibase啓動日誌

從日誌中可以看到Liquibase 在幫我們執行定義好的SQL,如果是第一次啓動,那麼數據庫會存在databasechangelogdatabasechangeloglock兩種表,從名字就可以看出,故而不作過多解釋

日誌表

2.SQL中的語法是創建一張person表和 兩次 INSERT 操作

SQL執行記錄

總結

目前很多大佬都寫過關於 SpringBoot 的教程了,如有雷同,請多多包涵,本教程基於最新的 spring-boot-starter-parent:2.0.3.RELEASE編寫,包括新版本的特性都會一起介紹…

說點什麼

  • 個人QQ:1837307557
  • battcn開源羣(適合新手):391619659
  • 微信公衆號(歡迎調戲):battcn

公衆號

個人博客:http://blog.battcn.com/

全文代碼:https://github.com/battcn/spring-boot2-learning/tree/master/chapter23

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章