SpringBoot整合Liquibase

1、是什么?

Liquibase官网

Liquibase是一个开源的数据库管理工具,可以帮助开发人员管理和跟踪数据库变更。它可以与各种关系型数据库和NoSQL数据库一起使用,并提供多种数据库任务自动化功能,例如数据库迁移、版本控制和监控。Liquibase还提供了一个Web界面,可以方便地管理和跟踪数据库变更。它支持Java、Python、Ruby等多种语言,可以轻松地集成到现有的开发环境中。

2、能干嘛?

Liquibase主要功能包括:

  • 数据库迁移:可以方便地将数据库从一个版本迁移到另一个版本。
  • 版本控制:可以跟踪数据库变更的历史记录,并可以根据需要回滚到以前的版本。
  • 监控:可以监控数据库变更,并在发生变更时收到通知。
  • 自动化:可以自动化数据库任务,例如在应用程序部署之前检查数据库完整性。

Liquibase可以帮助开发人员更加高效地管理数据库,并减少由于数据库变更而导致的错误。

Liquibase的优点:

  • 配置文件支持SQL、XML、JSON 或者 YAML
  • 版本控制按序执行
  • 可以用上下文控制sql在何时何地如何执行
  • 支持schmea的变更
  • 根据配置文件自动生成sql语句用于预览
  • 可重复执行迁移
  • 可插件拓展
  • 可回滚
  • 可兼容14中主流数据库如oracle,mysql,pg等,支持平滑迁移
  • 支持schema方式的多租户(multi-tenant)

3、怎么玩?

这里主要使用SpringBoot整合Liquibase实现对数据库进行版本管理

(1) 引入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ly</groupId>
    <artifactId>springboot-liquibase</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.1.0</version>
    </parent>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.33</version>
        </dependency>

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

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.28</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.18</version>
        </dependency>
    </dependencies>
</project>
(2) 配置数据源
package com.ly.config;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.Data;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;

import static com.ly.config.DataSourcesConfig.SPRING_DATASOURCE;

/**
 * @author ly (个人博客:https://www.cnblogs.com/ybbit)
 * @date 2023-07-22  16:28
 * @tags 喜欢就去努力的争取
 */
@ConfigurationProperties(prefix = SPRING_DATASOURCE)
@SpringBootConfiguration
@Data
public class DataSourcesConfig {

    public static final String SPRING_DATASOURCE = "spring.datasource";

    private String driverClassName;
    private String url;
    private String username;
    private String password;

    /**
     * 数据源配置
     *
     * @return
     */
    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(username);
        return dataSource;
    }
}

(3) 配置Liquibase
package com.ly.config;

import liquibase.integration.spring.SpringLiquibase;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;

/**
 * @author ly (个人博客:https://www.cnblogs.com/ybbit)
 * @date 2023-07-22  14:53
 * @tags 喜欢就去努力的争取
 */
@ConditionalOnProperty(value = "spring.profiles.active", havingValue = "dev")
@SpringBootConfiguration
public class LiquibaseConfig {

    public static final String CHANGE_LOG_PATH = "classpath:/liquibase/db.changelog-master.xml";

    @Bean
    public SpringLiquibase liquibase(DataSource dataSource) {
        SpringLiquibase liquibase = new SpringLiquibase();
        liquibase.setChangeLog(CHANGE_LOG_PATH);
        liquibase.setDataSource(dataSource);
        liquibase.setShouldRun(true);
        return liquibase;
    }

}
(4) 创建db.changelog-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.1.xsd">

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

<!--    <includeAll path="change/" relativeToChangelogFile="true"/>-->

    <!--加入一张test_create_table表-->
    <include file="classpath:liquibase/change/changelog_v1.0.xml"></include>

    <!--给test_create_table表加一个email字段-->
    <include file="classpath:liquibase/change/changelog_v2.0.xml"></include>

    <!--修改test_create_table表加email字段-->
    <include file="classpath:liquibase/change/changelog_v3.0.xml"></include>

    <!--向test_create_table表加一条数据-->
    <include file="classpath:liquibase/change/changelog_v4.0.xml"></include>

</databaseChangeLog>
(5) 创建每一项的变更文件(推荐把各个模块的变更都分门别类的整理好)

changelog_v1.0.xml

<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<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-latest.xsd">
    <!--
     changeSet:每一个changeSet对应一个数据库相关的操作
      author:修改人
      id:唯一
    -->
    <!--加入一张表【test_create_table】-->
    <changeSet author="ly" id="2023072201-1">
        <createTable remarks="用户表" tableName="test_create_table">
            <column autoIncrement="true" name="id" type="INT" remarks="主键">
                <constraints nullable="false" primaryKey="true" unique="true"/>
            </column>
            <column name="username" remarks="用户名" type="VARCHAR(32)">
                <constraints unique="true" nullable="false"/>
            </column>
            <column name="password" remarks="密码" type="VARCHAR(100)">
                <constraints unique="false" nullable="false"/>
            </column>
        </createTable>
    </changeSet>
</databaseChangeLog>

changelog_v2.0.xml

<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<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-latest.xsd">
    <changeSet author="ly" id="2023072202-1">
        <!--加入一个email字段-->
        <addColumn tableName="test_create_table">
            <column name="email" type="VARCHAR(32)" remarks="邮箱">
                <constraints nullable="true"/>
            </column>
        </addColumn>
    </changeSet>
</databaseChangeLog>

changelog_v3.0.xml

<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<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-latest.xsd">
    <changeSet author="ly" id="2023072203-1">
        <!--重命名email列名称-->
        <renameColumn tableName="test_create_table" oldColumnName="email" newColumnName="newEmail" columnDataType="VARCHAR(50)"/>
    </changeSet>
</databaseChangeLog>

changelog_v4.0.xml

<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<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-latest.xsd">
    <changeSet author="ly" id="2023072204-1">
        <!--插入一条数据-->
        <insert tableName="test_create_table">
            <column name="id" value="1"></column>
            <column name="username" value="zs"></column>
            <column name="password" value="123"></column>
            <column name="newEmail" value="zs@163.com"></column>
        </insert>
    </changeSet>
</databaseChangeLog>
(6) SpringBoot配置文件
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/qbb01
    username: root
    password: root
  profiles:
    active: dev
(7) Main
package com.ly;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

/**
 * @author ly (个人博客:https://www.cnblogs.com/ybbit)
 * @date 2023-07-22  14:52
 * @tags 喜欢就去努力的争取
 */
@EnableConfigurationProperties
@SpringBootApplication
public class LiquibaseApplication {
    public static void main(String[] args) {
        new SpringApplicationBuilder(LiquibaseApplication.class)
                .run(args);
    }
}
(7) 启动日志

image

(8) 数据库

image

image

4、ChangeSet标签集与作用

(1) add
标签说明
addAutoIncrement将已存在的列改为自增列
addColumn增加列
addDefaultValue增加列的默认值
addForeignKeyConstraint增加外键
addLookupTable创建外键的关联表
addNotNullConstraint增加非空值约束
addPrimaryKey增加主键
addUniqueConstraint增加唯一值约束
(2) create
标签说明
createIndex创建索引
createProcedure创建存储过程
createSequence创建序列
createTable创建表
createView创建视图
(3) drop
标签说明
dropAllForeignKeyConstraints删除全部外键约束
dropColumn删除列
dropDefaultValue删除默认值
dropForeignKeyConstraint删除某一外键约束
dropNotNullConstraint删除空值约束
dropPrimaryKey删除主键
dropProcedure删除存储过程
dropSequence删除序列
dropTable删除表
dropUniqueConstraint删除唯一约束
dropView删除视图
(4) rename
标签说明
renameColumn重命名列
renameSequence重命名序列
renameTable重命名表
renameView重命名视图
5、sql
标签说明
sqlsql语句
sqlFilesql文件
6、其他
标签说明
insert插入数据
update更新数据
delete删除数
empty空操作
executeCommand执行命名
alterSequence修改序列
customChange自定义操作,需自己实现
loadData导入csv数据至已存在的表中
loadUpdateData导入csv数据至表中,表不存在则新建
mergeColumns合并列
modifyDataType修改数据类型
output输出日志
setColumnRemarks增加列说明
setTableRemarks增加表说明
stop停止liquibase
tagDatabase打标签用于将来回滚

5、集成Maven插件

(1) 在pom.xml中加入下面的插件配置
<build>
        <plugins>
            <plugin>
                <groupId>org.liquibase</groupId>
                <artifactId>liquibase-maven-plugin</artifactId>
                <configuration>
                    <!--properties文件路径,该文件记录了数据库连接信息等-->
                    <propertyFile>src/main/resources/liquibase.properties</propertyFile>
                    <propertyFileWillOverride>true</propertyFileWillOverride>
                    <!--生成文件的路径-->
                    <outputChangeLogFile>src/main/resources/liquibase/change/changelog_base.xml
                    </outputChangeLogFile>
                </configuration>
            </plugin>
        </plugins>
    </build>
(2) 在resources目录下加入liquibase.properties配置文件
#要连接库配置信息
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/qbb01
username=root
password=root
#liquibase
changeLogFile=src/main/resources/liquibase/db.changelog-master.xml
(3) 根据当前配置的数据源生成changelog

image

(4) 结果

image

代码仓库:springboot-liquibase
  • 16
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Boot可以很方便地与Liquibase集成,以实现数据库版本控制和迁移。下面是整合步骤: 1. 添加Liquibase依赖 在pom.xml文件中添加Liquibase依赖: ``` <dependency> <groupId>org.liquibase</groupId> <artifactId>liquibase-core</artifactId> <version>3.8.9</version> </dependency> ``` 2. 配置Liquibase 在application.properties文件中添加Liquibase配置: ``` #Liquibase配置 spring.liquibase.change-log=classpath:/db/changelog/db.changelog-master.xml spring.liquibase.enabled=true spring.liquibase.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC spring.liquibase.user=root spring.liquibase.password=root ``` 其中,change-log属性指定Liquibase的changelog文件路径,url、user和password属性指定数据库连接信息。 3. 创建changelog文件 在resources/db/changelog目录下创建db.changelog-master.xml文件,用于定义数据库版本控制和迁移的变更集合。 例如: ``` <?xml version="1." 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.8.xsd"> <changeSet id="1" author="liquibase"> <createTable tableName="person"> <column name="id" type="bigint" autoIncrement="true"> <constraints primaryKey="true" nullable="false"/> </column> <column name="name" type="varchar(255)"> <constraints nullable="false"/> </column> <column name="age" type="int"/> </createTable> </changeSet> </databaseChangeLog> ``` 4. 运行应用程序 运行Spring Boot应用程序,Liquibase将自动检测数据库版本并执行相应的变更集。 以上就是Spring Boot整合Liquibase的步骤。 ### 回答2: Spring Boot是一款非常流行的Java框架,它为开发人员提供了一种简单、快速并且有效的方法来开发和部署Web应用程序。而Liquibase是一款专门用于管理数据库变更的工具,它提供了一种简单、可靠的方式来进行数据库的合并、迁移和关系升级等操作。本篇文章将会介绍如何使用Spring BootLiquibase进行数据库管理和变更。 1. 配置Liquibase 在pom.xml文件中,引入Liquibase的依赖。 ```xml <dependency> <groupId>org.liquibase</groupId> <artifactId>liquibase-core</artifactId> <version>[版本号]</version> </dependency> ``` 接下来,在application.properties文件中配置Liquibase ```properties spring.liquibase.enabled=true spring.liquibase.change-log=classpath:/db/changelog/db.changelog-master.xml spring.datasource.url=jdbc:mysql://localhost:3306/[数据库名]?useUnicode=true&characterEncoding=UTF8&allowMultiQueries=true&autoReconnect=true&failOverReadOnly=false&maxReconnects=5 spring.datasource.username=[用户名] spring.datasource.password=[密码] spring.datasource.driver-class-name=com.mysql.jdbc.Driver ``` 以上配置可根据实际情况自定义修改。其中,spring.liquibase.enabled=true表示启用Liquibasespring.liquibase.change-log指定Liquibase的master changelog文件;spring.datasource.*为数据源配置。 2. 编写Liquibase脚本 下面编写一个简单的Liquibase脚本,用于创建一个users表。 ```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.3.xsd"> <changeSet id="create-users-table" author="张三"> <createTable tableName="users"> <column name="id" type="bigserial" autoIncrement="true"> <constraints primaryKey="true"/> </column> <column name="username" type="varchar(50)"/> <column name="password" type="varchar(50)"/> <column name="email" type="varchar(50)"/> </createTable> </changeSet> </databaseChangeLog> ``` 以上脚本使用Liquibase的XML格式编写,用于创建一个名为users的表和其对应的字段。其中,id字段为自增主键,其他字段均为varchar类型。 3. 启动应用 现在,只需运行应用,并等待Liquibase执行创建表的脚本即可。Liquibase会在启动时检查数据库中是否存在对应的表,如果表不存在则会进行创建。如果已存在对应的表,则不会进行任何操作。通过运行时日志,可以看到Liquibase在检查和执行脚本的相关信息。 4. 变更数据库 当需要对数据库进行修改时,只需修改Liquibase脚本即可。Liquibase会自动检测修改并进行相应的变更,无需手动执行SQL语句。当需要更改数据表时,只需编写修改表结构的Liquibase脚本,例如新增一列。 ```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.3.xsd"> <changeSet id="add-email-to-users-table" author="张三"> <addColumn tableName="users"> <column name="email" type="varchar(50)"/> </addColumn> </changeSet> </databaseChangeLog> ``` 运行应用,Liquibase会自动检测到该变更操作,并进行相应的变更。 总结 通过Spring Boot整合Liquibase,我们可以轻松地将数据库管理和版本控制集成到应用中,从而提高开发效率、减少错误和风险。Liquibase提供了丰富的脚本语法和插件支持,为数据库管理带来了更多可能性。 ### 回答3: Spring Boot 是一种开箱即用的微服务框架,可以让开发者快速搭建并部署应用程序,而 Liquibase 是一个开源的数据库版本控制和迁移工具,可以帮助开发者管理数据库的变化与版本迭代。在实际的项目开发中,为了方便在集成开发环境(IDE)中更好地管理数据库的版本变更和迁移,通常需要 Spring Boot 整合 Liquibasespringboot整合liquibase)。 Spring Boot 整合 Liquibase 可以让开发者利用 Liquibase 强大的功能实现持续集成和部署,达到自动化管理数据库变更的效果,同时让开发者更加高效地进行开发。下面我们来了解一下 Spring Boot 整合 Liquibase 的具体实现步骤: ## 1. 引入依赖 在 pom.xml 文件中加入以下依赖: ```xml <dependency> <groupId>org.liquibase</groupId> <artifactId>liquibase-core</artifactId> <version>4.5.0</version> </dependency> ``` ## 2. 编写 Liquibase 配置文件 在 resources 目录下新建 liquibase 目录,并在该目录下新建 liquibase.properties 文件。该文件包含了一些 Liquibase 的配置信息,例如: ```properties changeLogFile=classpath:db/changelog/changelog-master.xml url=jdbc:mysql://localhost:3306/springdemo username=root password=root driver=com.mysql.cj.jdbc.Driver ``` ## 3. 编写 Liquibase changelog 在 resources 目录下新建 db/changelog 目录,并在该目录下新建一个 changelog-master.xml 文件,该文件描述了数据库的变更历史以及变更脚本: ```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-4.0.xsd"> <changeSet id="1" author="dbo"> <createTable tableName="person"> <column name="id" type="bigint" autoIncrement="true"> <constraints primaryKey="true" nullable="false"/> </column> <column name="name" type="varchar(255)"> <constraints nullable="false"/> </column> <column name="age" type="int"/> </createTable> </changeSet> </databaseChangeLog> ``` ## 4. 启动 Spring Boot 应用 当我们启动 Spring Boot 应用时,Liquibase 将会自动执行 changelog 中定义的变更脚本。例如,我们在命令行执行 mvn spring-boot:run 启动 Spring Boot,则会执行以下操作: 1. 根据 liquibase.properties 中的配置信息,创建与数据库的连接; 2. 根据 changelog-master.xml 中的定义,检查数据库的变更历史; 3. 根据 changelog-master.xml 中的定义,执行数据库的变更脚本,将其应用到数据库中; 4. 关闭与数据库的连接。 总之,Spring Boot 整合 Liquibase 提供了一个方便易用的数据库管理工具,可以帮助开发者更好地管理数据库变更的历史和版本,提高开发效率并保证数据完整性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值