In this tutorial, you will learn how to generate domain model classes (with Hibernate/JPA annotations) and Hibernate mapping files using Hibernate Reverse Engineering feature of Hibernate Tools. This makes programming with Hibernate easier as you can save a lot of time in creating mapped model classes and mapping files.

The following tools and software programs are used in this tutorial:

- JDK 1.8

- Eclipse IDE Oxygen (4.7.2)

- MySQL Database

- MySQL Connector J (JDBC Driver)

- Hibernate Tools

So suppose that you have JDK, Eclipse, MySQL database and MySQL JDBC Driver installed on your computer.

 

1. Creating MySQL Database

In this tutorial, we will use Hibernate Reverse Engineering feature to generate code for Java model classes from 3 tables in a MySQL database called mysales. The following ER diagram shows the structure and relationship among the tables:

ERDiagram

As you can see, the table user stands alone, whereas the tables category and product have one-to-many relationship. Let’s see how Hibernate Tools generate model classes and mapping files from these tables.

 

2. Installing Hibernate Tools in Eclipse IDE

First, you need to install Hibernate Tools which is a core component of JBoss Tools. In Eclipse IDE, click Help > Marketplace… In the Eclipse Marketplace dialog, type jboss tools in the search box and hit Enter. Scroll the result list until you see the JBoss Tools 4.5.2.Final as shown below:



Eclipse Marketplace - JBoss Tools

 

Click Install button to install JBoss Tools plugins for Eclipse. In the next screen, Confirm Selected Features, you can choose only Hibernate Tools from the list:

Choose Hibernate Tools

 

Then click Confirm. In the next screen, check “I accept the terms of the license agreement”, and click Finish:

Accept Terms

 

The installation progress appears in Eclipse’s status bar. If a Security Warning dialog appears, click Install anyway:

Security Warning

 

Wait until the installation completes, and click Restart Now to restart the IDE when asked.

Once installed, there’s a new perspective called Hibernate. Click Window > Perspective > Open Perspective… and choose Hibernate:

Open Hibernate Perspective

Click OK, and you see Eclipse switches to Hibernate perspective with views like Hibernate Configurations, Query Parameters, Hibernate Query Result, etc.

 

3. Creating a New Hibernate Console Configuration

Before continuing, make sure you have your project opened in Eclipse and have the MySQL JDBC Driver JAR file (e.g. mysql-connector-java-5.1.45-bin.jar) present in the project’s classpath (or via Maven dependency).

The Hibernate Reverse Engineering feature requires a Hibernate/JPA configuration file exists (hibernate.cfg.xml or persistence.xml).

For example, create the Hibernate configuration file hibernate.cfg.xml under the source folder (src\main\java) with the following content:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mysales</property>
        <property name="hibernate.connection.password">password</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    </session-factory>
</hibernate-configuration>
Now, in the Hibernate Configurations view, click the Add Configuration… button:

Add Configuration

 

In the Edit Configuration dialog, click Browse… butto\ to choose the project:

Choose Project

 

Click OK, you can see a new configuration called hibernate is added. Expand the Database node, you can see the structure of the mysales database appears:

HibernateConfiguration

That means Hibernate Tools uses the connection information provided in the hibernate.cfg.xml file to connect to the database successfully.

NOTE: You can create a Hibernate/JPA configuration file by using the wizards in the Edit Configuration dialog.

 

4. Generating Model Classes

Now, you can generate code from the newly added Hibernate console configuration. In Eclipse, click the arrow in the Hibernate Run button and choose Hibernate Code Generation Configurations…:

Run Hibernate Code Generation

In the Hibernate Code Generation Configurations dialog, you need to create a new launch configuration. Select the Hibernate Code Generation node and click New button:

New Launch Configuration

A new launch configuration called New_configuration is added. In the Main tab, do the following things:

- Choose the configuration hibernate under Console configuration.

- Choose the directory that contains generated code. Here I choose the src\main\java folder of the current project.

- Check the option Reverse engineer from JDBC connection, and type the Java package name that contains the generated code (it will be created if not exists).

Until now, the screen should look like this:

New Launch Configuration - Main

 

And under the Exporters tab, check two options Generate EJB3 annotations and Domain code (.java) if you want to generate only model classes with JPA annotations. The screen should look like this:

New Launch Configuration - Exporter

 

Then you can see there are 3 model classes corresponding to the 3 tables in the database, were generated in the Package Explorer view:

Generated Code

 

NOTE:You can choose to generate mapping files (.hbm.xml) and DAO code, as shown in the Exporters tab. Choose the options depending on your need.

You can also run the code generation by clicking Run > Hibernate Code Generation… > Hibernate Code Generation Configurations…


5. Using the Generated Code

The generated code of the model classes use JPA annotations, so make sure you have Hibernate core dependency in the project’s POM file, for example:

<dependency>
	<groupId>org.hibernate</groupId>
	<artifactId>hibernate-core</artifactId>
	<version>5.2.12.Final</version>
</dependency>
 

The following is full generated code of the User.java class:

package net.codejava.hibernate;
// Generated Mar 9, 2018 11:58:58 AM by Hibernate Tools 5.2.8.Final

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * User generated by hbm2java
 */
@Entity
@Table(name = "user", catalog = "mysales")
public class User implements java.io.Serializable {

	private Integer userId;
	private String email;
	private String password;

	public User() {
	}

	public User(String email, String password) {
		this.email = email;
		this.password = password;
	}

	@Id
	@GeneratedValue(strategy = IDENTITY)

	@Column(name = "user_id", unique = true, nullable = false)
	public Integer getUserId() {
		return this.userId;
	}

	public void setUserId(Integer userId) {
		this.userId = userId;
	}

	@Column(name = "email", nullable = false, length = 45)
	public String getEmail() {
		return this.email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	@Column(name = "password", nullable = false, length = 10)
	public String getPassword() {
		return this.password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}
 

And the generated code of the Category.java class is as follows:

package net.codejava.hibernate;
// Generated Mar 9, 2018 11:58:58 AM by Hibernate Tools 5.2.8.Final

import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

/**
 * Category generated by hbm2java
 */
@Entity
@Table(name = "category", catalog = "mysales")
public class Category implements java.io.Serializable {

	private Integer categoryId;
	private String name;
	private Set products = new HashSet(0);

	public Category() {
	}

	public Category(String name) {
		this.name = name;
	}

	public Category(String name, Set products) {
		this.name = name;
		this.products = products;
	}

	@Id
	@GeneratedValue(strategy = IDENTITY)

	@Column(name = "category_id", unique = true, nullable = false)
	public Integer getCategoryId() {
		return this.categoryId;
	}

	public void setCategoryId(Integer categoryId) {
		this.categoryId = categoryId;
	}

	@Column(name = "name", nullable = false, length = 45)
	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@OneToMany(fetch = FetchType.LAZY, mappedBy = "category")
	public Set getProducts() {
		return this.products;
	}

	public void setProducts(Set products) {
		this.products = products;
	}

}
As you can see, Hibernate Reverse Engineering feature automatically detects the one-to-many relationship between Category and Product, so it generates the code accordingly:

private Set products = new HashSet(0);

@OneToMany(fetch = FetchType.LAZY, mappedBy = "category")
public Set getProducts() {
	return this.products;
}
 

And the code of the Product.java class is generated as follows:

package net.codejava.hibernate;
// Generated Mar 9, 2018 11:58:58 AM by Hibernate Tools 5.2.8.Final

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

/**
 * Product generated by hbm2java
 */
@Entity
@Table(name = "product", catalog = "mysales")
public class Product implements java.io.Serializable {

	private Integer productId;
	private Category category;
	private String name;
	private float price;

	public Product() {
	}

	public Product(Category category, float price) {
		this.category = category;
		this.price = price;
	}

	public Product(Category category, String name, float price) {
		this.category = category;
		this.name = name;
		this.price = price;
	}

	@Id
	@GeneratedValue(strategy = IDENTITY)

	@Column(name = "product_id", unique = true, nullable = false)
	public Integer getProductId() {
		return this.productId;
	}

	public void setProductId(Integer productId) {
		this.productId = productId;
	}

	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "category_id", nullable = false)
	public Category getCategory() {
		return this.category;
	}

	public void setCategory(Category category) {
		this.category = category;
	}

	@Column(name = "name", length = 45)
	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Column(name = "price", nullable = false, precision = 12, scale = 0)
	public float getPrice() {
		return this.price;
	}

	public void setPrice(float price) {
		this.price = price;
	}

}
As you can see, the code for one-to-many relationship is generated properly:

private Category category;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "category_id", nullable = false)
public Category getCategory() {
	return this.category;
}
You can use the generated code directly in your project. It saves us a lot of time, isn’t it?

That’s how to generate Java model classes from database tables using Hibernate Reverse Engineering feature of Hibernate Tools in Eclipse IDE.

 

References:

Hibernate Tools Home Page

Hibernate Tools Reference Guide

 You can also watch the video version of this tutorial here:

 

Recommended course:

 

Other Hibernate Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment

   


Comments 

#7TRAORE2021-06-02 11:00
Thank you for your explanation regarding the generation of entities. Your example allowed me to understand a lot of things. Once again I say thank you.
Quote
#6mostafa hegazy2020-04-20 11:00
look i did reverse the data from db but there is no jpa annotaion appear like this _____
where @Entity and relation between classes its not appear ???????????
Quote
#5Nam2020-03-30 23:25
Hi FredeBR,
I will check Hibernate tools with latest versions of JDK and Eclipse.
When installing JBoss tools, try to install everything - not just Hibernate Tools.
Quote
#4FredeBR2020-03-28 10:28
Your article is very good. But I couldn't run with newer versions of eclipse (2019-12), JDK 11 and Hibernate 5.4. The error message appears:
"java.lang.NullPointerException
at org.hibernate.eclipse.console.views.properties.HibernatePropertySourceProvider.getPropertySource(HibernatePropertySourceProvider.java:52)"
I changed to version 5.2 of hibernate and the same problem continues. What could be happening?
Could you please update your tutorial to these latest versions?
Quote
#3Manoj2020-01-15 17:08
Thanks a lot for the article. It saved my time.
Quote