September 15, 2020

Let’s assume we have a running project using liquibase for the schema migrations and we want to add a new column to the user column. Our initial approach could look something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
databaseChangeLog:
  - changeSet:
      id: add-required-column
      author: thomas
      changes:
        - addColumn:
            tableName: user
            columns:
            - column:
                name: enabled
                type: boolean
                constraints:
                  nullable: false

Unforuntatly this will not work if there are already entries in our table, as the NotNullConstraint will fail immediately and cannot be applied. Instead we need a two step approach:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
databaseChangeLog:
  - changeSet:
      id: add-required-column
      author: thomas
      changes:
        - addColumn:
            tableName: user
            columns:
            - column:
                  name: enabled
                  type: boolean
        - addNotNullConstraint:
            tableName: user
            columnName: enabled
            defaultNullValue: true

With the defaultNullValue property liquibase will fill up the entries with the given value. We can use other datatypes like String as well.

Did you know that you can create your next Spring Boot application with Bootify.io? Define your own database model and get the JPA entities and liquibase script out-of-the-box.

Contact