A while ago I posted an article that showed how to generate a database schema from JPA annotations. Since I didn’t get the hibernate3 maven plugin working back then I used the antrun plugin as a workaround. Thanks to the help of a reader the plugin works now, so an update is in order.
Since the last article the scenario hasn’t changed: I want to generate DDL scripts for creating a database schema from JPA annotations. The created schema can then be tweaked as necessary and used in the production environment. Like the old antrun solution, the maven plugin uses the ant task from Hibernate Tools, so the resulting schema is the same.
This is how it works. Edit your
pom.xml and add the plugin configuration:
<build> <plugins> <!-- other plugins ... --> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>hibernate3-maven-plugin</artifactId> <version>2.2</version> <executions> <execution> <phase>process-classes</phase> <goals> <goal>hbm2ddl</goal> </goals> </execution> </executions> <configuration> <components> <component> <name>hbm2ddl</name> <implementation>jpaconfiguration</implementation> </component> </components> <componentProperties> <persistenceunit>Default</persistenceunit> <outputfilename>schema.ddl</outputfilename> <drop>false</drop> <create>true</create> <export>false</export> <format>true</format> </componentProperties> </configuration> </plugin> </plugins> </build>
Make sure that the persistence unit’s name in
pom.xml (“Default” in this example) is consistent with the name assigned in
persistence.xml. Additionally, you have to set the
hibernate.dialect property or Hibernate won’t be able to generate a DDL script that’s compatible with your type of database.
Schema creation is executed in the
process-classes phase, so you’ll find the schema in
target/hibernate3/sql/schema.ddl after running
mvn package (or any later phase). An alternative is to remove the
<executions> element and to run the hbm2ddl goal from the command line:
The plugin offers a lot more than just schema creation. See the plugin documentation for more information.