How to use Hibernate Tools Maven Plugin to generate JPA entities from an existing database

Hibernate Tools is a toolset for Hibernate that provides easy generation, testing and prototyping of your Hibernate or JPA mapped projects. It can be used to run queries, browse mappings and generate code for your data projects. Hibernate Tools is a core component of JBoss Tools.

The most powerful feature of Hibernate Tools is a database reverse engineering tool that can generate domain model classes and Hibernate mapping files, annotated EJB3 entity beans, HTML documentation etc.

Reverse engineering can be achieved using an integrated suite of Eclipse plugins, together with a unified Ant task for integration into the build cycle. Alternatively, one can also use the Hibernate Tools Maven Plugin to provide hibernate tools reverse engineering and code/schema generation abilities.

In this article, we will be covering the Hibernate Tools Maven Plugin approach in detail using Spring Boot with a MySQL database.

The Setup

Go to https://start.spring.io and generate a project with the following settings.

Open the project in your favourite IDE. I will be using Visual Studio Code. To setup visual studio code for spring boot development, you can follow this tutorial.

MySQL Database

Add the following docker-compose.yml file to your project root folder.

Run docker-compose up -d. This will setup a MySQL instance in the background with the database demo that is accessible at localhost:3306 with the username user and password password.

To learn more in detail on how this works, you can refer this tutorial.

Hibernate Tools Maven Plugin

Add the following plugin code to your pom.xml.

Add the following files to your ${project.basedir}/src/main/resources folder.

hibernate.properties contains the database connection details.

hibernate.reveng.xml is used to control the reverse engineering, e.g. naming of properties, which tables to include or exclude etc.

Use Cases

Now, let’s look at different use cases and see how to achieve reverse engineering for them using hibernate tools.

Convert Table to Entity

Add/Execute the following table in your MySQL database.

The above table contains set of columns with auto increment, primary key and unique key constraints.

Run mvn hibernate-tools:hbm2java to generate the JPA entities. The JPA entities will be generated to the ${project.build.directory}/generated-sources/ folder i.e. target/generated-sources will now have the Users.java JPA entity file as below.

Enable Hibernate Annotations (ejb3 & jdk5)

The configuration ejb3 enables usage annotations from javax.persistence and org.hibernate.annotations.

The configuration jdk5 enables usage of JDK 5 constructs such as generics and static imports.

ejb3 & jdk5 configurations are disabled by default. To enable these, add the following configurations to the hibernate tools maven plugin in pom.xml as below.

Run mvn hibernate-tools:hbm2java and now Users.java is updated with hibernate annotations and static imports as below.

Change Output Directory (packageName & outputDirectory)

If you have multiple tables, it requires manual effort to copy the JPA entities from the default output folder to the desired project folder every time there is some change in the database. Instead, one can have the JPA entities generated directly to the desired project folder along with the project package name using the outputDirectory and packageName configurations.

The configuration packageName enables us to provide a default package name to use when mappings for classes are created.

The configuration outputDirectory enables us to specify the directory to which the JPA entities should be generated.

Add these configurations to the hibernate tools maven plugin in pom.xml as below.

Now, when you run mvn hibernate-tools:hbm2java, the JPA entities are generated to the ${project.basedir}/src/main/java/com/jonamlabs/hibernatetoolsdemo/entity folder with package com.jonamlabs.hibernatetoolsdemo.entity; added to all the classes.

Control Reverse Engineering (revengFile)

As part of the initial plugin setup, we had added an hibernate.reveng.xml without any configurations. The hibernate.reveng.xml file is used to enable finer degree of control of the reverse engineering process. The full list of features that are supported in the hibernate.reveng.xml file are as below.

  • Specific table configuration ( <table>)
    Use to specify how a table should be reverse engineered. It allows control over the naming of a class for the specific table, provides a way to specify which identifier generator should be used for the primary key and more.
  • Table filters ( <table-filter>)
    Use to specify matching rules for performing general filtering and setup of tables, e.g. include or exclude specific tables based on the schema or even a specific prefix.
  • Schema Selection ( <schema-selection>)
    Use to determine which schemas the reverse engineering should try and process
  • Type mappings ( <type-mapping>)
    Use to specifies how the JDBC types found in the database should be mapped to Hibernate types. e.g.  java.sql.Types.VARCHAR with a length of 1 can be mapped to the Hibernate type  yes_no, or  java.sql.Types.NUMERIC can generally just be converted to the Hibernate type  long.

You can refer this link for detailed explanation of all these features.

Now, let’s look at use cases that require these configurations.

Modify Table Class Name (<table>)

By default, the JPA entity classes are generated using the same name as their tables. If you want to rename them, say users table should be generated as User.java instead of Users.java, add the following configuration to your hibernate.reveng.xml file as below.

The catalog attribute in the table tag is required. Without this, the table class name override will NOT work.

Now, when you run mvn hibernate-tools:hbm2java, the users table gets generated as User.java as below.

Exclude Tables (<table-filter>)

If you want to exclude certain tables from being reverse engineered, you can add configurations into the hibernate.reveng.xml file as below.

Include Schemas (<schema-selection>)

By default the reverse engineering will read all schemas. This can be inefficient on databases with many schemas. To significantly speed-up the reverse engineering, we can use the  <schema-selection> tag to limit which schemas are processed in the hibernate.reveng.xml file as below.

Change Hibernate Type (<type-mapping>)

To control/override how JDBC types found in the database are mapped to hibernate types, we can use the <type-mapping> tag in the hibernate.reveng.xml file as below.

The number of attributes specified and the sequence of the  sql-type tags are important. This is because Hibernateā„¢ will search for the most specific first, and if no specific match is found it will seek from top to bottom when trying to resolve a type mapping.

Remove Generated Date (templatePath)

All the generated classes will have a timestamp in the file indicating when it was generated as below.

If the classes are being generated into a project folder and are part of source control, then every time we run mvn hibernate-tools:hbm2java, all the files would be marked as modified due to the timestamp change even if there is no change in the database. This can be removed by modifying the templates used for generating the POJOs. Here are the steps.

  1. Go to https://mvnrepository.com/artifact/org.hibernate/hibernate-tools/5.4.20.Final
  2. Download the jar
  1. Extract hibernate-tools-5.4.20.Final.jar
  2. Copy the pojo folder and its contents into ${project.basedir}/src/main/resources/templates project folder
  1. Open Pojo.ftl

Pojo.ftl is the template used for generating JPA entities. Notice the second line that contains the ${date} . This is replaced by the generated timestamp when we run mvn hibernate-tools:hbm2java.

  1. Edit Pojo.ftl by removing the ${date} as below
  1. Add the templatePath configuration pointing to the edited templates for the hibernate tools maven plugin in pom.xml as below
  1. Now, when you run mvn hibernate-tools:hbm2java, the generated classes will not have the generated timestamp as below

Convert Foreign Key Relationships

Add/Execute the following table that has a foreign key reference to the initially created users table.

Now, when you run mvn hibernate-tools:hbm2java, the JPA entities are generated with @OneToMany and @ManyToOne annotations as below.

To rename Users as User and UserAddresses as UserAddress, add the following configurations to your hibernate.reveng.xml file as below.

Conclusion

The working project can be found here on Github.

References

Leave a Reply

Your email address will not be published. Required fields are marked *