Thursday, October 17, 2013

Maven: Generating DDL Scripts from JPA Annotations

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.
Add the following to your pom.xml:


hibernate3-maven-plugin 2.2 hbm2ddl jpaconfiguration Default schema.ddl false true false true
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.

Wednesday, October 16, 2013

Red Sector A

All that we can do is just survive
All that we can do to help ourselves
Is stay alive...


Sunday, October 13, 2013

Catcher In The Rye



When all is said and done
We're not the only ones
Who look at life this way
That's what the old folks say
But every time I see them
Makes me wish I had a gun
If I thought that I was crazy
Well I guess I'd have more fun
(Guess I'd have more fun)