Java’s persistence API (JPA) makes object-relational mapping very convenient. Persistence providers like Hibernate can create tables and sequences automatically saving lots of tedious work at development time. However, in production systems automatic schema creation isn’t desired.
In many cases you want to tune the schema a bit, like adding an index for speeding up common access paths, renaming constraints and the like. Additionally, an application should run with as little DB privileges as possible, so it’s quite common that CREATE TABLE or other DDL/SQL statements are simply not permitted.
That’s where the Hibernate3 Maven Plugin can give you a good starting point for your optimizations.
Prerequisites
This article is for you if
- you use JPA annotations on your entities
- your persistence provider is Hibernate 3
Configuration
The plugin wraps an Ant task from Hibernate Tools that analyzes your JPA entities and creates a database schema for them.
Then adjust your persistence.xml file in src/main/resources/META-INF to set the SQL dialect to use for the DDL statements:
The example above uses HSQL (the embedded database that ships with JBoss), but you’ll likely need a different dialect for your production setup. You can get a list of supported dialects from Hibernate’s API documentation. Also make sure that the persistence unit’s name (Default in this example) matches with the plugin configuration and your persistence.xml.
Now execute the hbm2ddl goal from the command line to create the schema:
mvn hibernate3:hbm2ddl
You will find your schema in target/hibernate3/sql/schema.ddl.
Alternatives
If you want to execute hibernate3::hbm2ddl automatically as part of your normal build, you can tie the hbm2ddl goal to the process-classes phase. There’s an example on the plugin’s homepage.
Further Reading
Traditionally, Maven plugins aren’t documented that well. But since hibernate3-maven-plugin is just a thin wrapper around Hibernate Tools, you can find documentation there.
There’s a lot more the plugin can do, especially if you’re not using JPA annotations, by the way.
No comments:
Post a Comment