SpringBoot 整合 liquibase

SpringBoot 整合 liquibase

LiquiBase是一个用于数据库重构和迁移的开源工具,通过日志文件的形式记录数据库的变更,然后执行日志文件中的修改,将数据库更新或回滚到一致的状态。它的目标是提供一种数据库类型无关的解决方案,通过执行schema类型的文件来达到迁移。其有点主要有以下:

  • 支持几乎所有主流的数据库,如MySQL, PostgreSQL, Oracle, Sql Server, DB2等;
  • 支持多开发者的协作维护;
  • 日志文件支持多种格式,如XML, YAML, JSON, SQL等;
  • 支持多种运行方式,如命令行、Spring集成、Maven插件、Gradle插件等。

liquibase 官方文档地址:http://www.liquibase.org/documentation/index.html

一、引入依赖

先在 pom 文件里引入依赖

<dependency>
  <groupId>org.liquibase</groupId>
  <artifactId>liquibase-core</artifactId>
</dependency>

二、指定配置文件位置

在代码中新建一个 LiquibaseConfig 类,用于配置 Liquibase,指定配置文件的位置。

import javax.sql.DataSource;
import liquibase.integration.spring.SpringLiquibase;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class LiquibaseConfig {
   

  @Bean
  public SpringLiquibase liquibase(DataSource dataSource) {
   
    SpringLiquibase liquibase = new SpringLiquibase();
    liquibase.setDataSource(dataSource);
    //指定changelog的位置,这里使用的一个master文件引用其他文件的方式
    liquibase.setChangeLog("classpath:liquibase/master.xml");
    liquibase.setContexts("development,test,production");
    liquibase.setShouldRun(true);
    return liquibase;
  }

}

三、编写配置文件

目录结构:

在这里插入图片描述

src/main/resources 下新建一个文件夹:liquibase,用来存放跟 liquibase 相关的文件。

master.xml

然后在 liquibase 文件夹下新建 master.xml 作为主文件。

<databaseChangeLog
        xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
         http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">

    <includeAll path="liquibase/changelogs/" relativeToChangelogFile="false"/>

</databaseChangeLog>

includeAll 标签可以把一个文件夹下的所有 changelog 都加载进来。如果单个加载可以用 include

includeAll 标签里有两个属性:pathrelativeToChangelogFile

Attribute Description
file Name of the file to import required
relativeToChangelogFile Is the file path relative to the root changelog file rather than to the classpath. Defaults to “false” since 1.9

path (在 include 标签里是 file):指定要加载的文件或文件夹位置

relativeToChangelogFile :文件位置的路径是否相对于 root changelog 是相对路径,默认 false,即相对于 classpath 是相对路径。

changelog

另在 liquibase 文件夹下新建 changelogs 文件夹用来存放 changelog。

这里新建一个 changelog-1.0.xml

<databaseChangeLog
        xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
         http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">

    
  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值