首页 > 解决方案 > 在 Spring Boot 中使用 liquibase mongodb 扩展

问题描述

尝试在 Spring Boot 中使用 liquibase-mongodb 扩展,但运行迁移对我的数据库没有影响。

在 pom 文件中添加了 liquibase-core、liquibase-mongodb 扩展和 ongo-java-driver 作为依赖项。

这是我的变更日志文件:

<?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-4.0.xsd
    http://www.liquibase.org/xml/ns/dbchangelog-ext 
    http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd">

<changeSet id="first" author="andrei">
    <ext:createCollection collectionName="myCollection">
        <ext:options>
            {
            validator: {
            $jsonSchema: {
            bsonType: "object",
            required: ["name", "address"],
            properties: {
            name: {
            bsonType: "string",
            description: "The Name"
            },
            address: {
            bsonType: "string",
            description: "The Address"
            }
            }
            }
            },
            validationAction: "warn",
            validationLevel: "strict"
            }
        </ext:options>
    </ext:createCollection>
    </changeSet>
</databaseChangeLog>

我尝试注入 bean SpringLiquibase,但它需要我提供一个 DataSource,它是一个接口,而 Liquidbase 的 mongo 扩展不提供此接口的实现。

@Bean
public SpringLiquibase liquibase() {
    MongoLiquibaseDatabase db = new MongoLiquibaseDatabase();
    SpringLiquibase liquibase = new SpringLiquibase();
    liquibase.setChangeLog("classpath:/db/changelog/db.changelog-master.yaml");
    //How to do this?
    // liquibase.setDataSource();
    liquibase.setShouldRun(true);
    return liquibase;
}

有没有人有一个使用Spring的liquidbase mongodb扩展的工作示例?

标签: springmongodbspring-bootmigrationliquibase

解决方案


最简单的方法可能是使用org.springframework.jdbc.datasource.SimpleDriverDataSourceand liquibase.ext.mongodb.database.MongoClientDriver

MongoClientDriver 是 liquibase-mongodb 扩展的一部分,并根据java.sql.DriverLiquibase 的需要调整 MongoClient 到接口。

这应该允许您创建 SimpleDriverDataSource 并将其传递给 liquibase,例如:

SimpleDriverDataSource dataSource = new SimpleDriverDataSource(new MongoClientDriver(), YOUR_URL, YOUR_USERNAME, YOUR_PASSWORD);
liquibase.setDataSource(dataSource);

推荐阅读