SpringBoot支持了两种数据库结构版本管理与迁移,一个是flyway,一个是liquibase。其本身也支持sql script,在初始化数据源之后执行指定的脚本,本章是基于 Liquibase 开展…
- Liquibase
开发人员将本地开发机器上的基于文本的文件中的数据库更改存储在本地数据库中。Changelog文件可以任意嵌套,以便更好地管理,每个变更集通常包含描述应用于数据库的更改/重构的更改。Liquibase支持对支持的数据库和原始SQL生成SQL的描述性更改。通常,每个变更集应该只有一个更改,以避免可能导致数据库处于意外状态的自动提交语句失败。
- 使用
在平时开发中,无可避免测试库增加字段或者修改字段以及创建表之类的,环境切换的时候如果忘记修改数据库那么肯定会出现不可描述的事情,这个时候不妨考虑考虑Liquibase,闲话不多说,上代码
- pom.xml
4.0.0
org.springframework.boot
spring-boot-starter-parent
1.5.6.RELEASE
com.battcn
battcn-boot-liquibase
1.0-SNAPSHOT
UTF-8
1.8
1.1.1
1.3.0
org.springframework.boot
spring-boot-starter-web
com.zaxxer
HikariCP
org.mybatis.spring.boot
mybatis-spring-boot-starter
${mybatis-spring-boot.version}
org.liquibase
liquibase-core
mysql
mysql-connector-java
5.1.38
org.springframework.boot
spring-boot-starter-test
test
- application.yml
spring:
application:
name: battcn-boot-liquibase
datasource:
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/liquibase?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true
#我这里使用的是默认路径,如果默认路径其实可以不配置,有兴趣可以看 LiquibaseProperties 的源代码
liquibase:
change-log: classpath:db/changelog/db.changelog-master.yaml
liquibase.change-log 配置文件的路径,默认值为classpath:/db/changelog/db.changelog-master.yaml
liquibase.check-change-log-location 是否坚持change log的位置是否存在,默认为true.
liquibase.contexts 逗号分隔的运行时context列表.
liquibase.default-schema 默认的schema.
liquibase.drop-first 是否首先drop schema,默认为false
liquibase.enabled 是否开启liquibase,默认为true.
liquibase.password 目标数据库密码
liquibase.url 要迁移的JDBC URL,如果没有指定的话,将使用配置的主数据源.
liquibase.user 目标数据用户名
- db.changelog-master.yaml
databaseChangeLog:-changeSet:
id:1author: Levin
changes:-createTable:
tableName: person
columns:-column:
name: id
type:intautoIncrement:trueconstraints:
primaryKey:truenullable:false
-column:
name: first_name
type: varchar(255)
constraints:
nullable:false
-column:
name: last_name
type: varchar(255)
constraints:
nullable:false
-changeSet:
id:2author: Levin
changes:-insert:
tableName: person
columns:-column:
name: first_name
value: Marcel-column:
name: last_name
value: Overdijk-changeSet:
id:3author: 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 演变而来的,官方是支持 xml,yaml,json 三种格式,写法也比较简单
- Application.java
packagecom.battcn;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;/***@authorLevin
* @date 2017-08-19.*/@SpringBootApplicationpublic classApplication {public static voidmain(String[] args) {
SpringApplication.run(Application.class, args);
}
}
- 测试
1.启动Application.java中的main方法
从日志中可以看到Liquibase 在帮我们执行定义好的SQL,如果是第一次启动,那么数据库会存在databasechangelog 和 databasechangeloglock两种表,从名字就可以看出,故而不作过多解释
2.SQL中的语法是创建一张person表和 两次 INSERT 操作