Tag Archives: hbm2ddl

10 Mrz

Generate DDL script of JPA persistence unit in Maven using hbm2ddl

Recently, I was facing the task of generating the DDL script of a JPA domain model in a Maven build. Of course, there is Hibernate’s hbm2ddl to actually perform the DDL generation, however, I did not know any Maven plugin capable of invoking hbm2ddl. After some research, I found out that this is achievable via an Ant task (i.e. use the Ant plugin for Maven), or via the hibernate3-maven-plugin. I decided to go with the hibernate3-maven-plugin, although all it does is to create a respective Ant task and invoke Ant on this task. Here is my Maven configuration for generating the DDL of my persistence unit during the Maven build:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>hibernate3-maven-plugin</artifactId>
    <version>3.0</version>
    <executions>
        <execution>
            <id>generate-ddl</id>
            <goals>
                <goal>hbm2ddl</goal>
            </goals>
            <phase>process-classes</phase>
        </execution>
    </executions>
    <configuration>
        <hibernatetool>
            <jpaconfiguration persistenceunit="my-persistence-unit"/>
            <classpath>
                <path location="${project.build.directory}/classes" />
            </classpath>
            <hbm2ddl
                    export="false"
                    update="false"
                    drop="false"
                    create="true"
                    outputfilename="my-persistence-unit.ddl"
                    delimiter=";"
                    format="true"
                    haltonerror="true" />
        </hibernatetool>
    </configuration>
    <dependencies>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
    </dependencies>
</plugin>

This configuration invokes hbm2ddl with the correct classpath and parameters during Maven’s process-classes phase, and creates the file target/sql/hibernate3/my-persistence-unit.ddl containing all DDL scripts of the configured JPA persistence unit.