Using Liquibase with Hibernate

Hibernate is an object-relational mapping (ORM) tool that can be used alongside Liquibase to provide a persistent framework for a relational database.

The purpose of this document is to guide you through the process of creating a new Liquibase project and integrating it into your Hibernate JPA setup.

Supported versions

  • 6.x: liquibase-hibernate6
  • 5.x: liquibase-hibernate5

Prerequisites

  • Download and install Maven.

Create a new Liquibase project with Hibernate

We will be creating a Maven project for this tutorial. To configure a Liquibase project for Hibernate, perform the following steps:

  1. Specify the database URL in the Liquibase properties file. Liquibase does not parse the URL. You can either specify the full database connection string or specify the URL using your database's standard JDBC format:
  2. url=hibernate:ejb3:com.liquibase.hibernate.tutorial.jpa

    Tip: To apply a Liquibase Pro key to your project, add the following property to the Liquibase properties file: licenseKey: <paste code here>

  3. Create a pom.xml file in your project directory and add the following content to the file:
  4. Create a JPA configuration file at META-INF/persistence.xml. The persistence.xml file should contain the following content:
  5. Create the folder src/main/java/com/liquibase, which will be used for entity classes. In this directory, create a file House.java in a text editor and add the following content:
  6. Create a second file Item.java in the same directory and paste the following:
  7. Install the application using the mvnw install command, or mvnw.cmd install for Windows.
  8. The generated JAR is what is referenced in the liquibase.properties file: classpath=target\\hibernate-liquibase-0.0.1-SNAPSHOT.jar
  9. Next, generate a dbchangelog.xml file from Hibernate in your project folder:
  10. liquibase.propertiesmvn liquibase:diff
  11. A file will be generated at src/main/resources/db/migrations/20221208174852_changelog.xml. You can move and rename it to src/main/resources/dbchangelog.xml, then run mvn install again.
  12. Verify the project configuration by running the Liquibase status command. Open a command prompt and go to the project folder. Run the following command:
  13. liquibase.propertiesmvn liquibase:status
    Example output:
    5 changesets have not been applied to DBUSER@jdbc:h2:file:~/test
  14. Now apply the changeset using the command
  15. mvn liquibase:update
  16. From a database UI tool, ensure that your database contains the table you added along with the DATABASECHANGELOG table and DATABASECHANGELOGLOCK table.
  17. You can run the application using command mvn exec:exec and it shall work successfully.

Finished

You have successfully configured your project and can begin creating changesets to migrate changes to your database using Hibernate.

Source code is available at: https://github.com/juliuskrah/hibernate-liquibase

Related links