LiquiBase
是一个用于数据库重构和迁移的开源工具,通过 changelog
文件 的形式记录数据库的变更,然后执行 changelog
文件 中的修改,将数据库更新或回滚到一致的状态。
- 支持几乎所有主流的数据库,如MySQL、PostgreSQL、Oracle、Sql Server、DB2等
- 支持多开发者的协作维护;
- 日志文件支持多种格式;如XML、YAML、SON、SQL等
- 支持多种运行方式;如命令行、Spring 集成、Maven 插件、Gradle 插件等
导入依赖
<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>
属性配置
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', '哈哈', '呵呵');