java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot使用Liquibase数据库版本管理

SpringBoot项目使用Liquibase数据库版本管理方式

作者:刘火锅

Liquibase是开源数据库版本管理工具,支持多数据库及多格式变更日志,实现变更追踪、上下文执行、文档生成等功能,需配置目录结构及master.xml文件,注意@PostConstruct初始化顺序问题,建议用CommandLineRunner替代

数据库版本管理

概述

Liquibase 是一个用于数据库重构、变更管理和版本控制的开源工具。

它通过对数据库变更进行版本化管理,支持多人协作开发、多分支合并,并提供多种数据库类型的支持。

特点

集成步骤

1. 添加依赖

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

2. 创建目录结构

在项目 resources 目录下创建 liquibase 目录用于存放 liquibase 相关的配置文件,在 liquibase 目录下创建 changelog 目录存放所有 changelog 文件

src/main/resources/
    └── liquibase/
        ├── master.xml
        └── changelog/
            ├── common/
            │   ├── master.xml
            │   └── 20230110_common_init_table.sql
            └── other_module/

3.创建master.xml文件

liquibase 目录下的 master.xml 为 liquibase 的入口,通过 include 标签将其它的 master.xml文件引入进来。

<?xml version="1.0" encoding="utf-8"?>
<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.4.xsd">

    <!--
    1:includeAll 标签可以把一个文件夹下的所有 changelog 都加载进来。如果单个加载可以用 include。
    2:includeAll 标签里有两个属性:path 和 relativeToChangelogFile。
        2.1:path (在 include 标签里是 file):指定要加载的文件或文件夹位置
        2.2:relativeToChangelogFile :文件位置的路径是否相对于 root changelog 是相对路径,默认 false,即相对于 classpath 是相对路径。
    -->

   <include file="liquibase/changelogs/common/master.xml"/>

</databaseChangeLog>

具体模块的master.xml

<?xml version="1.0" encoding="utf-8"?>
<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.4.xsd">

    <!--
    1:includeAll 标签可以把一个文件夹下的所有 changelog 都加载进来。如果单个加载可以用 include。
    2:includeAll 标签里有两个属性:path 和 relativeToChangelogFile。
        2.1:path (在 include 标签里是 file):指定要加载的文件或文件夹位置
        2.2:relativeToChangelogFile :文件位置的路径是否相对于 root changelog 是相对路径,默认 false,即相对于 classpath 是相对路径。
    -->

   <changeSet id="liquibase/20230110_common_init_table.sql" author="xxxx">
        <sqlFile path="liquibase/20230110_common_init_table.sql"/>
    </changeSet>

</databaseChangeLog>

id:执行id,执行文件名称

4. 应用配置

指定 liquibase 的 changelog文件

spring:
  liquibase:
    enabled: false # 是否启用
    change-log: classpath:/liquibase/master.xml 

changelog文件命名规则

注意事项

初始化顺序问题

问题描述:

解决方案:

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文