Skip to content

Using Hibernate Maven Plugin to generate database schema

Updated: at 05:43 AM

In integration tests, I often need to setup the database to a determined state before every test case. In order to do that, we need to create database schema which reflect your current models and then populate with proper data. In today post, I will show you how to generate the database schema from your Hibernate models by using the Hibernate Maven Plugin (3.0). In my shop, we are still using the “old-school” Hibernate mapping: XML!. The reason is we want to keep our models pristine (no annotations or whatever). We use Maven as our build tool, so here is the plugin configuration that works:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>hibernate3-maven-plugin</artifactId>
    <version>3.0</version>
    <executions>
        <execution>
            <id>create-schema</id>
            <phase>process-test-resources</phase>
            <goals>
                <goal>run</goal>
            </goals>
            <configuration>
                <hibernatetool destdir="${project.basedir}/src/test/resources/">
                    <configuration
                        configurationfile="${project.basedir}/src/test/resources/hibernate.cfg.xml" />
                    <hbm2ddl create="true" export="false"
                        drop="true" outputfilename="schema.sql"
                        format="true" console="false" />
                </hibernatetool>
            </configuration>
        </execution>
    </executions>
</plugin>

We use Spring to configure Hibernate directly, the hibernate.cfg.xml used here is just for this purpose only (ie. generating the database schema). Here is it just for the sake of completeness:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="dialect">org.hibernate.dialect.HSQLDialect</property>
        <property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
        <property name="connection.url">jdbc:hsqldb:mem:sample_db</property>
        <property name="connection.username">sa</property>
        <property name="connection.password"></property>
    </session-factory>
</hibernate-configuration>

There are other operations that you can utilize with Hibernate Tools. For more information, please refer to Hibernate Tools documentation and the hibernate3-maven-plugin site.