Database migration using Liquibase in Spring MVC application

In the previous tutorial, I introduced you to Liquibase, a library that helps us to perform database migration for any Java application. In this tutorial, I will guide you to implement database migration using Liquibase with Spring MVC application!

First, I will create a new Spring MVC project using Spring Tool Suite 3 as an example.

Result:

Database migration using Liquibase in Spring MVC application

I will use the Maven Jetty Plugin to run this project.

The results when I run this project will be as follows:

Database migration using Liquibase in Spring MVC application

Để làm việc với Liquibase, các bạn cần khai báo dependency của nó:

To work with a database in Spring, we need to add spring-orm dependency:

I will use PostgreSQL database in this example:

By default, Liquibase supports integration with Spring framework. By declaring the bean of the SpringLiquibase class in the Spring container, when running the application using the Spring framework, Liquibase will automatically perform the database migration for us!

You can configure the bean of SpringLiquibase class in Spring container using XML configuration (in file /src/main/webapp/WEB-INF/spring/root-context.xml) as follows:

Our task is to just configure the bean for dataSource and changeLog only!

I will configure dataSource for PostgreSQL database in Spring container (in file /src/main/webapp/WEB-INF/spring/root-context.xml) as follows:

The dataSource configuration I will not mention in detail here. You can read more this tutorial JPA and Spring framework.

From the value of changeLog in the SpringLiquibase configuration above, you can understand that you need to create a changelog file of db-changelog.xml in the src/main/resources directory.

I will define the contents of the changelog file to add the clazz table as follows:

Now, rerun the application, check the database, you will see the following results:

Database migration using Liquibase in Spring MVC application

Add Comment