Database Migration with Liquibase

We’ll use Liquibase for database schema management:

  1. Add Liquibase dependency to your build.gradle:

    dependencies {
        implementation 'org.liquibase:liquibase-core'
    }
    
  2. Create a db/changelog folder in your src/main/resources directory.

  3. Create a db.changelog-master.xml file in the changelog folder:

    <?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"
            xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
                    http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.8.xsd">
    
        <includeAll path="db/changelog/changes/"/>
    
    </databaseChangeLog>
    
  4. Add change set files in src/main/resources/db/changelog/changes/, using the naming convention yyyy-MM-dd-description.xml. For example, 2024-08-25-create-users-table.xml:

    <?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"
            xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
                    http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.8.xsd">
    
        <changeSet id="2024-08-25-create-users-table" author="yourname">
            <createTable tableName="users">
                <column name="id" type="bigint" autoIncrement="true">
                    <constraints primaryKey="true" nullable="false"/>
                </column>
                <column name="username" type="varchar(50)">
                    <constraints nullable="false"/>
                </column>
                <column name="email" type="varchar(100)">
                    <constraints nullable="false"/>
                </column>
            </createTable>
        </changeSet>
    
    </databaseChangeLog>
    

    Note

    NB! Once a change set has been committed and applied to any environment, it must not be modified. Always create new change sets for modifications.

  5. Configure Liquibase in your application.properties:

    spring.liquibase.change-log=classpath:db/changelog/db.changelog-master.xml
    

This setup provides a solid foundation for database management in your Spring Boot application using PostgreSQL and Liquibase. The use of XML format for Liquibase changesets offers better IDE support with autocompletion and validation against the XSD schema, particularly useful in IntelliJ IDEA. The date-based naming convention for changeset files (yyyy-MM-dd-description.xml) helps avoid conflicts when merging branches and provides a clear chronological order of changes.