Springboot 整合 Liquibase

571人浏览 / 0人评论

参考:

https://www.cnblogs.com/guangsheng/p/13815173.html

依赖

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

配置

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/liquibase?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&&createDatabaseIfNotExist=true
    username: root
    password: 123456
  liquibase:
    enabled: true
    change-log: classpath:/db/changelog/master.xml

在/db/changelog/目录下创建master.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
        xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
    <!-- includeAll可以把db/changelog/migrate/内所有的文件全部引用并执行 -->    
    <includeAll path="db/changelog/migrate/" relativeToChangelogFile="false" />
    <!-- 或者引用单个文件 -->
    <!-- <include file="db/changelog/20220621_test_init_database.xml" relativeToChangelogFile="false"/> -->
</databaseChangeLog>

然后在db/changelog/migrate/20220621_test_init_database.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.5.xsd">
    <preConditions onFail="WARN">
        <not>
            <tableExists tableName="area"/>
        </not>
    </preConditions>
    <!--  如果要添加或修改字段、备注等信息,要另外新增加一个changeSet,id可以是1、2、3等,不要动原先的changeSet -->
    <changeSet id="1" author="jbritian">
        <createTable tableName="area">
            <column autoIncrement="true" name="id" type="INT">
                <constraints nullable="false" primaryKey="true" primaryKeyName="pk_area"/>
            </column>
            <column name="name" type="VARCHAR(30)" remark="姓名"/>
            <column name="parent_id" type="INT"/>
        </createTable>
    </changeSet>
</databaseChangeLog>

全部评论