demig0d
demig0d

Reputation: 1181

Proper way to use liquibase along with Spring JPA/Hibernate?

I'm a bit confused. I want to use a relational database (Postgres or MySQL) along with Spring JPA. I like the annotations, how you can define models and relationships between them, joins, and use repositories. From what I've read, it seems that using Hibernate's auto DDL generation feature is not recommended and should be disabled. This makes sense, I'd like to track database changes in code via liquibase, which is much more stable.

Now to the confusing part which I'm having trouble understanding. Can I still use the JPA Annotations to define things like @OneToMany or @JoinColumn? This would be doing exactly what I'd be doing via changesets in liquibase. Should we still use the annotations, or can we rather?

Could someone please explain this workflow or point to documentation that outlines a proper way to use Liquibase, Spring Data JPA in combination?

Upvotes: 5

Views: 3154

Answers (1)

Jens Schauder
Jens Schauder

Reputation: 81940

It is not only ok but probably the most common use case to use Liquibase AND annotations.

The annotations have a very different purpose than Liquibase. They describe how to map pieces of your Java code to your database schema.

Liquibase creates and evolves this database schema.

The annotations contain no information about different versions of your schema. This is why you shouldn't use Hibernates DDL generation for your actual production schema, although it might be fine for development and testing to some extent. Of course, at some point you should test your app with the schema generated exactly the way it will get generated for production.

Liquibase has no information about how mapping from your schema to Java objects and back should be done.

Of course, there is overlap. If your annotations say that a certain field should be mapped to the column x in table t Liquibase should create that table with that column (and the type expected by Hibernate).

The way I normally do this is:

  1. Create my Java object model
  2. Use Hibernate to create DDL scripts/ the schema. Review the schema and tune the mapping until the schema looks as desired.
  3. Create the DDL once more and use that as a basis to configure my migration tool (Liquibase or otherwise). Tune the script again in the process for things not relevant for the mapping: Names of constraints and indexes, additional indexes and constraints, privileges, storage options.
  4. Makes sure there are tests in place that test basic CRUD operations with the Liquibase migrations.

Of course, if you start with the database model your process might look very different.

Upvotes: 8

Related Questions