spring boot+liquibase踩坑记录

前言

Spring boot本身支持liquibase,所以pom文件中添加依赖后,application.yml/application.properties定制配置信息即可,不配置使用spring boot默认配置,这样就可以用了,项目启动的时候就会去运行指定目录下的数据库更改文件,使用中还是踩了两个坑,在此记录下来。

配置

照例还是先把配置过程 写下来

  • 添加pom依赖
<!-- 未指定版本,默认用了当前最新版本:3.5.3->
<dependency>
    <groupId>org.liquibase</groupId>
    <artifactId>liquibase-core</artifactId>
</dependency>
  • application.yml配置(可选)
    不配置默认去resource/db/changelog下找db.changelog-master.yaml文件,我不习惯用yaml文件配置数据库变更记录,所以换成官方推荐推荐的xml
    这里有我遇到 的第一个坑~~

    liquibase:
    enabled: true
    change-log: classpath:/db/changelog/db.changelog-master.xml

  • 创建liquibase变更文件
    在resource/db/changelog目录下新建db.changelog-master.xml
    这里写图片描述

  • 写变更记录
    官方文档上写支持xml,yaml,json甚至是sql,我用的是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"
        xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
        xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd
        http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd">

    <preConditions>
        <runningAs username="username"/>
    </preConditions>

    <changeSet id="2" author="Issac">
        <addColumn tableName="user">
            <column name="status" type="tinyint(1)" remarks="状态" defaultValue="0"/>
        </addColumn>
    </changeSet>

</databaseChangeLog>
  • 重启项目
    下面就是遇到 的两个坑:
    • spring boot版本与yml文件配置项要匹配:
      当时系统报错找不到db/changelog/db.changelog-master.yaml文件,说明我在application.yml中指定的配置未生效(当时yml文件中配置是spring.liquibase.change-log=),去spring官网查看,与最新的官网文档配置一致,后来看到当前项目spring boot版本是1.5.8。去官网翻1.5.8的文档,才发现配置项前面没有spring前缀。
    • mysql驱动高版本问题
      再重启项目,报了个新错误“Column name pattern can not be NULL or empty”,原因是项目用了6.x的mysql驱动,默认nullNamePatternMatchesAll为false。liquibase需要这个参数打成true,所以spring.datasource.url后面加上nullNamePatternMatchesAll=true即可。

猜你喜欢

转载自blog.csdn.net/liubingyu12345/article/details/78891772