Skip to content
Advertisement

Running liquibase within Java code

For some reason there’s no documentation on running liquibase inside Java code. I want to generate tables for Unit tests.

How would I run it directly in Java?

e.g.

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

Advertisement

Answer

It should be something like (taken from 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
        }
    }
}

There are multiple implementation of ResourceAccessor depending on how your changelog files should be found.

Advertisement