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表并存入了数据。

猜你喜欢

转载自www.cnblogs.com/liconglong/p/11728767.html