In this tutorial we shall see how to generate JPA Annotations/Hibernate Mappings from Database Schema, coding JPA Entities (with Annotations) or Hibernate Entities (with Mappings) is a tedious task especially when the number of table is more or when we migrate an existing Application from other ORM/JDBC to Hibernate Framework.
To solve the above problem we have plugin for Eclipse called Hibernate Tools which will generate JPA Entities (with Annotations) or Hibernate Entities (with Mappings) for us. The below instructions help us to use the plugin.
1. Install the Plugin
Go to Eclipse Marketplace by Help –> Eclipse Marketplace
From the options select the plugin based on your Eclipse version (in my case it is already installed 😀 ).
2. Hibernate Console Configuration
Create a new Java Project. This will be the project where our JPA Annotations/Hibernate Mappings will be saved by the plugin.
In Eclipse select File –> New –> Other search for Hibernate Console Configuration select Next and proceed
Hibernate Console Configuration
Select New as highlighted above
select the appropriate database.
Enter Database Details
and enter the Database URL Credentials.
Select the Add driver button highlighted above and select the driver version.
remove any existing Jar Entries and Add a new entry for MySQL Connector jar and click OK.
Choose Driver Jar
In the next screen just click Test Connection for success.
Select a Dialect
Select an appropriate Dialect as per your database. (in my case it is MySQL InnoDB). Click Finish.
After the above step Hibernate Console is now configured successfully.
3. Hibernate Code Generation
Switch your Eclipse to Java Perspective and in the Eclipse Tab select Code Generation Configuration as below.
Hibernate Code Generation
In the next window select New Configuration and under the Exporters Tab select the options as below.
In the Main Tab select the Console Configuration just now created, Output Directory , select Reverse Engineer from Database and enter the Package name.
Click on Setup for reveng.xml and Create new… and then select the Core Java Project we created earlier. In the next screen click on Refresh. Select all the Tables under the schema and include as below.
Click on Finish.
In the Hibernate Code Generation Configuration window press Run
In the Eclipse Project and you could find the Reverse Engineered Files in the Output folder entered.
I hope this has been useful for you and I’d like to thank you for reading. If you like this article, please leave a helpful comment and share it with your friends.