Hibernate Tools – JPA Entity generation

Recently i was reviewing and trying some examples using the Hibernate Tools. More specifically, i was trying their latest version (5.0.0.CR1) in order to generate some JPA entity POJOs, out of a database schema.

Hibernate Tools, can either be used programmatically from their Java API, or using their pre-defined ANT tasks. The below examples demonstrate the programmatic way and a Mavenized way, by invoking ANT from within Maven.

I used an in-memory HSQL database, with two very simple tables. A Users table with an ID and a name and an Address table with an ID, some fields and a foreign key to the Users table, mimicking a many-to-one dependency.

The code that starts up the HSQL server and creates the tables can be found in GitHub.

As mentioned above the Hibernate Tools can be invoked programmatically. Initially i found it a bit tricky as i hadn’t realized i needed to invoke the JDBC Configuration step before i invoked the POJOs generation step. Probably, this is needed in order for the tool to read the Hibernate configuration file, and identify the database and its schema. The configuration that is needed is actual rather trivial:

  • Set the destination folder
  • Point the tool to the hibernate configuration file, in order to pickup the database details
  • Invoke the JDBCConfigurationTask in order to identify the database schema
  • Invoke the Hbm2JavaGenerationTask in order to generate the JPA entities out of the above database schema

A sample code that does the above is shown below:

The java code that is generated for the two database tables is the below:

The whole process can be made as part of a maven compilation step. This is done using the ANT tasks that are provided. The relevant section of the pom.xml file is the below. Additionally, using the maven helper plugin the generated classes can automatically be added on the project’s classpath, bulletproffing the application ( and automating the tedious task of re-generating the entities ) of future changes to the database schema.

The complete example can be found in GitHub.