繁体   English   中英

在 Java 代码内运行 liquibase

[英]Running liquibase within Java code

由于某种原因,没有关于在 Java 代码中运行 liquibase 的文档。 我想为单元测试生成表格。

我如何直接在 Java 中运行它?

例如

Liquibase liquibase = new Liquibase()
liquibase.runUpdates() ?

它应该是这样的(取自 liquibase.integration.spring.SpringLiquibase 源):

java.sql.Connection c = YOUR_CONNECTION;
Liquibase liquibase = null;
try {
    Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(c))
    liquibase = new Liquibase(YOUR_CHANGELOG, new FileSystemResourceAccessor(), database);
    liquibase.update();
} catch (SQLException e) {
    throw new DatabaseException(e);
} finally {
    if (c != null) {
        try {
            c.rollback();
            c.close();
        } catch (SQLException e) {
            //nothing to do
        }
    }
}

ResourceAccessor 有多种实现,具体取决于应如何找到更改日志文件。

我找到了一种方法,以实现建立使用或者行家或Java数据库。 上面的示例使用FileSystemResourceAccessor() ,不幸的是,如果您部署一个需要从 jar 本身设置数据库的应用程序,那么您最终不得不将 jar提取为 zip 作为解决方法,因为这些 liquibase文件只存在于 jar 中。 这意味着您的 jar 最终是不可移植的,并且您必须在要设置数据库的任何地方使用maven

使用这个结构:

src/main/resources/liquibase/db.changelog-master.xml src/main/resources/liquibase/changelogs/...

您的数据库变更日志主文件可能如下所示:

<?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">

    <!-- <includeAll path="src/main/resources/liquibase/changelogs"/> -->
    <include file="changelogs/my-date.1.sql" relativeToChangelogFile="true"/>
</databaseChangeLog>

您可以将此部分用于pom.xml ,以确保mvn install也将设置您的 liquibase 数据库。

<plugin>
   <groupId>org.liquibase</groupId>
   <artifactId>liquibase-maven-plugin</artifactId>
   <version>3.5.1</version>
   <configuration>
      <changeLogFile>liquibase/db.changelog-master.xml</changeLogFile>
      <driver>org.postgresql.Driver</driver>
      <url>${jdbc.url}</url>
      <username>${jdbc.username}</username>
      <password>${jdbc.password}</password>
   </configuration>
   <executions>
      <execution>
         <phase>process-resources</phase>
         <goals>
            <goal>update</goal>
         </goals>
      </execution>
   </executions>
</plugin>

使用ClassLoaderResourceAccessor()而不是FileSystemResourceAccessor()

public static void runLiquibase() {

    Liquibase liquibase = null;
    Connection c = null;
    try {
        c = DriverManager.getConnection(DataSources.PROPERTIES.getProperty("jdbc.url"),
                DataSources.PROPERTIES.getProperty("jdbc.username"),
                DataSources.PROPERTIES.getProperty("jdbc.password"));

        Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(c));
        log.info(DataSources.CHANGELOG_MASTER);
        liquibase = new Liquibase(DataSources.CHANGELOG_MASTER, new ClassLoaderResourceAccessor(), database);
        liquibase.update("main");
    } catch (SQLException | LiquibaseException e) {
        e.printStackTrace();
        throw new NoSuchElementException(e.getMessage());
    } finally {
        if (c != null) {
            try {
                c.rollback();
                c.close();
            } catch (SQLException e) {
                //nothing to do
            }
        }
    }
}

您可以在测试中使用 h2-database 进行练习(路径“db/changelog.xml”是 main/resources/db/changelog.xml):

import liquibase.Contexts;
import liquibase.Liquibase;
import liquibase.database.Database;
import liquibase.database.DatabaseFactory;
import liquibase.database.jvm.JdbcConnection;
import liquibase.exception.LiquibaseException;
import liquibase.resource.ClassLoaderResourceAccessor;
import org.junit.jupiter.api.Test;

import java.sql.DriverManager;
import java.sql.SQLException;

public class LiquidBaseTest {

    @Test
    public void testExecuteLiquidBaseScripts() throws SQLException, LiquibaseException {
        java.sql.Connection connection = DriverManager.getConnection("jdbc:h2:mem:");

        try {
            Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
            Liquibase liquibase = new Liquibase("db/changelog.xml", new ClassLoaderResourceAccessor(), database);
            liquibase.update(new Contexts());
        } finally {
            if (connection != null) {
                connection.rollback();
                connection.close();
            }
        }
    }

}
public static void runLiquibase() throws Exception {
    Map<String, Object> config = new HashMap<>();

    Scope.child(config, () -> {
        try {
            Connection connection = DriverManager.getConnection("your database connection url");
            Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
            Liquibase liquibase = new liquibase.Liquibase("database/db.changelog-main.xml", new ClassLoaderResourceAccessor(), database);
            liquibase.update(new Contexts(), new LabelExpression());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    });

}

此代码将帮助您根据版本管理多个变更日志,并且您可以提供主文件的参考。

我遵循以下结构。

  • src/main/resources/database/db.changelog-main.xml
  • src/main/resources/database/changelogs/db.changelog-v-1.0.0.xml
  • src/main/resources/database/changelogs/db.changelog-v-1.0.1.xml

参考链接https://docs.liquibase.com/workflows/liquibase-community/using-liquibase-java-api.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM