Create and update DDL statements for JPA (Hibernate 4) using maven

In a Java8 project which uses JPA (with Hibernate4), it is non-trivial to get the create and update DDL statements. With the following configuration, it is possible to do this using:

mvn hibernate3:hbm2ddl

My project contains this persistence.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="" version="2.0"
    <persistence-unit name="fluxtock">
            <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL9Dialect" />

Unfortunately, this configuration cannot be used as it does not directly define the connection. Also, this file references a Hibernate4 specific dialect. The maven plugin for Hibernate tools only supports Hibernate3, so is cannot handle this dialect. As solution, I put a hibernate.cfg.xml file in the test resources. This configuration is only used by the maven plugin.

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        <!-- DataSource & Connection info. -->
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/zzz</property>
        <property name="hibernate.connection.username">zzz</property>
        <property name="hibernate.connection.password">zzz</property>
        <property name="hibernate.connection.pool_size">1</property>
        <!-- All our Hibernate mapping XML files. -->
        <mapping package="my.package.domain" />
        <mapping class="my.package.DomainClass1" />
        <mapping class="my.package.DomainClass2" />

You need to define a mapping line for each domain object and possibly also for the package (to assure that the package-info file is read, this can contain type mappings etc). Remember to add and remove domain classes when needed.

Using this configuration, You can include the maven plugin. You have to add a suitable Hibernate version as dependency. In my case (being on Java8) I also needed to switch javassist to a java8 capable version (to complicate things, the groupId had changed).

            <hbm2ddl create="true" export="false" outputfilename="create-ddl.sql" format="true" console="true">
                <configuration configurationfile="src/test/resources/hibernate.cfg.xml"/>
            <hbm2ddl update="true" export="false" outputfilename="update-ddl.sql" format="true" console="true">
                <configuration configurationfile="src/test/resources/hibernate.cfg.xml"/>

Leave a Reply

Your email address will not be published. Required fields are marked *

question razz sad evil exclaim smile redface biggrin surprised eek confused cool lol mad twisted rolleyes wink idea arrow neutral cry mrgreen