在Java代码中运行liquibase

时间:2012-05-16 13:57:11

标签: java liquibase

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

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

e.g。

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

3 个答案:

答案 0 :(得分:36)

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

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有多种实现方式,具体取决于应该如何找到更改日志文件。

答案 1 :(得分:1)

我找到了一种使用 maven或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
            }
        }
    }
}

答案 2 :(得分:1)

您可以在测试中使用h2-数据库进行练习(路径“ 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();
            }
        }
    }

}