The version of Spring Boot we will be using is 2.7.4
. The dependencies we need are as follows.
<dependency>
<groupId>org.liquibase.ext</groupId>
<artifactId>liquibase-mongodb</artifactId>
<version>4.15.0</version>
</dependency>
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
<version>4.15.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>3.4.3</version>
</dependency>
We need to define the url to connect to the Mongo database, the username and password of the user that has writing and reading permissions and also the changeLogFilePath
which is the path to the changelog file. In the following example, the changelog file is stored in resources > db > changelog
.
String url = "";
String username = "";
String password = "";
String changeLogFilePath = "classpath:db/changelog/changelog.json";
Next, we need to create the MongoLiquibaseDatabase
class which opens the connection to the Mongo database.
MongoLiquibaseDatabase database = (MongoLiquibaseDatabase) DatabaseFactory.getInstance().openDatabase(
url, username, password, null,
new ClassLoaderResourceAccessor());
We create the Liquibase
class which offers the methods and functions to operate using liquibase onto Mongo. We pass to it the MongoLiquibaseDatabase
object we created above.
Liquibase liquibase = new Liquibase(changeLogFilePath, new ClassLoaderResourceAccessor(), database);
Now, we can execute the changelog
file.
List<ChangeSet> changeSetsList = liquibase.listUnrunChangeSets(null, null);
if (!changeSetsList.isEmpty()) {
liquibase.update("");
}
In the above method, we check if there are any unrun changesets
. If there are, we execute the update
method that executes the new updates on the changelog
file.
To make all the pieces together, look at the following code that uses try-with-resources
to ensure the close of connection to the Mongo database in case of failure.
try (MongoLiquibaseDatabase database = (MongoLiquibaseDatabase) DatabaseFactory.getInstance().openDatabase(
url, username, password, null,
new ClassLoaderResourceAccessor());
Liquibase liquibase = new Liquibase(changeLogFilePath, new ClassLoaderResourceAccessor(), database);) {
List<ChangeSet> changeSetsList = liquibase.listUnrunChangeSets(null, null);
if (!changeSetsList.isEmpty()) {
liquibase.update("");
}
} catch (LiquibaseException e) {
log.error("error running liquibase {}", e.getMessage());
}
The changelog
file might be as follows.
{
"databaseChangeLog": [
{
"include": {
"file": "db/changelog/01-create-test.json"
}
},
{
"include": {
"file": "db/changelog/02-populate-test.json"
}
}
]
}