目前 Spring Boot
支持较好的两款工具分别是 flyway
、liquibase
,支持 sql script
,在初始化数据源之后执行指定的脚本代码
或者脚本文件
,本章基于 Liquibase
…
LiquiBase
是一个用于数据库重构和迁移的开源工具,通过 changelog文件
的形式记录数据库的变更,然后执行 changelog文件
中的修改,将数据库更新或回滚到一致的状态。
主要特点
在平时开发中,无可避免测试库增加字段或者修改字段以及创建表之类的,环境切换的时候如果忘记修改数据库那么肯定会出现 不可描述的事情
,这个时候不妨考虑考虑Liquibase
。
官方文档:http://www.liquibase.org/documentation/index.html
利用 Spring Boot
集成 Liquibase
,避免因粗心大意导致环境迁移时缺少字段….
依赖 spring-boot-starter-jdbc
目的是为了让 liquibase
能够获得 datasource
,这里换成 mybatis
、hibernate
等也是一样,主要偷懒不想写配置….
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-jdbc
mysql
mysql-connector-java
org.liquibase
liquibase-core
只要依赖了 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
更多配置
classpath:/db/changelog/db.changelog-master.yaml
change log
的位置是否存在,默认为true.schema
drop schema
(默认 false
)liquibase
(默认为 true
)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
INSERT INTO `person` (`id`, `first_name`, `last_name`) VALUES ('2', '哈哈', '呵呵');
上面的
yaml
文件其实就是从下面的XML
演变而来的,官方是支持xml
,yaml
,json
三种格式,写法也比较简单
传送门(官方给出了三种写法格式,依样画葫芦就可以了):http://www.liquibase.org/documentation/changes/sql_file.html
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
在帮我们执行定义好的SQL,如果是第一次启动,那么数据库会存在databasechangelog
和 databasechangeloglock
两种表,从名字就可以看出,故而不作过多解释
2.SQL中的语法是创建一张person
表和 两次 INSERT
操作