Java Hibernate Reverse Engineering Tutorial with Eclipse and MySQL
- Details
- Written by Nam Ha Minh
- Last Updated on 30 November 2023   |   Print Email
- 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: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: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: In the Edit Configuration dialog, click Browse… butto\ to choose the 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: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…: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: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: 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: Then you can see there are 3 model classes corresponding to the 3 tables in the database, were generated in the Package Explorer view: 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 Reference Guide
You can also watch the video version of this tutorial here:
Recommended course:
Other Hibernate Tutorials:
- How to customize Hibernate Reverse Engineering Code Generation
- Java Hibernate JPA Annotations Tutorial for Beginners
- Hibernate Hello World Tutorial for Beginners with Eclipse and MySQL
- Hibernate One-to-One Association on Primary Key Annotations Example
- Hibernate One-to-Many Using Join Table XML Mapping Example
- Hibernate Many-to-Many Association with Extra Columns in Join Table Example
- Hibernate Enum Type Mapping Example
- Hibernate Binary Data and BLOB Mapping Example
- Hibernate Basics - 3 ways to delete an entity from the datastore
- Hibernate Query Language (HQL) Example
Comments
where @Entity and relation between classes its not appear ???????????
I will check Hibernate tools with latest versions of JDK and Eclipse.
When installing JBoss tools, try to install everything - not just Hibernate Tools.
"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?