Category Archives: Liquibase

Automatic Database Diffs of your Domain Model

One of the (many) nice thing of using a proper ORM is the ability to create automatic database schemas from your domain model. For example, in EclipseLink, this is acheived with the SchemaManager class. All you need is a persistence unit name and let there be it!

If we season this a bit with some little magic from the amazing Liquibase project, with some simple steps we can make automatic structual diffs of our domain model! Let’s take a look at the algorithm we use in [ki]DOIT.

In order to simplify database versioning we have a simple naming convention. Let’s say we have a persistence unit named foo.dev. We’ll (finally) find a (mvn) folder structure as follows:

/src/main/resources/dbchangelog/foo.dev/db.changelog-master.xml/src/main/resources/dbchangelog/foo.dev/db.changelog-initial.xml

These files will sound familiar to you if you’ve already used Liquibase. If not, what are you waiting for?

If you are using the diff project you’ll notice you have a dependency to hsqldb. This is used to simplify db generation without the need of additional installation.

Let’s go with (a simplified version of) the algorithm then:

  1. Is there a db.changelog-master.xml?
    • No: Fresh start. Generate the initial database.
    • Yes: Diff. Generate the database with current changelog.
  2. Generate the new database with the changes you’ve made to the domain model.
  3. Ask Liquibase to generate your diff.
  4. The generated file will be /src/main/resources/dbchangelog/foo.dev/db.changelog-[TIMESTAMP].xml. Inspect any possible mistakes. You’ll find little :)

Too simple? Yes!! And it works like a charm. Currently, the only main issue is some arbitrary changes on indexes if you use them.