SpringBoot--數據庫管理與遷移(LiquiBase)


  隨着開發時間積累,一個項目會越來越大,同時表結構也越來越多,管理起來比較復雜,特別是當想要把一個答的項目拆分成多個小項目時,表結構拆分會耗很大的精力;如果使用LiquiBase對數據庫進行管理,那么就會大大提升遷移效率,還是以剛才的拆分項目為例,如果使用Liquibase,則只需要將指定模塊的表文件遷移走即可。

  接下來就是使用Springboot實現Liquibase。

  1、導入依賴

        <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>

  2、配置項

spring:
  profiles:
    active: test
  datasource:
    url: jdbc:mysql://***.76:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false
    username: root
    password: ***
  liquibase:
    enabled: true
    change-log: classpath:/db/changelog/db.changelog-master.yml

  3、定義db.changelog-master.yml

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

  4、由於也支持依賴外部文件,一次新建一個sql文件

INSERT INTO `person` (`id`, `first_name`, `last_name`) VALUES ('3', 'test', 'test2');

  5、運行項目

  可以看到在項目啟動時,liquibase新建了兩張表DATABASECHANGELOG、DATABASECHANGELOGLOCK,用來存儲表結構變化的日志,同時根據配置文件創建了person表並存入了數據。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM