How to generate Hibernate mapping files & annotation with Hibernate Tools

In this article, we show you how to use Hibernate / JBoss Tools to generate Hibernate mapping files (hbm) and annotation code from database automatically.

Tools in this article

  1. Eclipse v3.6 (Helios)
  2. JBoss / Hibernate Tools v3.2
  3. Oracle 11g
  4. JDK 1.6
Note
Before proceed, please Install Hibernate / JBoss Tools in Eclipse IDE.

1. Hibernate Perspective

Open your “Hibernate Perspective“. In Eclipse IDE, select “Windows” >> “Open Perspective” >> “Others…” , choose “Hibernate“.

2. New Hibernate Configuration

In Hibernate Perspective, right click and select “Add Configuration…

In “Edit Configuration” dialog box,

  1. In “Project” box, click on the “Browse..” button to select your project.
  2. In “Database Connection” box, click “New..” button to create your database settings.
  3. In “Configuration File” box, click “Setup” button to create a new or use existing “Hibernate configuration file”, hibernate.cfg.xml.
Eclipse Hibernate Tools

See your list of your tables in “Hibernate Perspective“.

Eclipse Hibernate Tools

Sample of “hibernate.cfg.xml“, connect to Oracle 11g database.


<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
  <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
  <property name="hibernate.connection.url">jdbc:oracle:thin:@127.0.0.1:1521:MKYONG</property>
  <property name="hibernate.connection.username">mkyong</property>
  <property name="hibernate.connection.password">password</property>
  <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
  <property name="hibernate.default_schema">MKYONG</property>
 </session-factory>
</hibernate-configuration>

3. Hibernate Code Generation

Now, you are ready to generate the Hibernate mapping files and annotation codes.

– In “Hibernate Perspective”, click “Hibernate code generation” icon (see below figure) and select “Hibernate Code Generation Configuration”

Hibernate Code Generation

– Create a new configuration, select your “console configuration” (configured in step 2), puts your “Output directory” and checked option “Reverse engineer from JDBC Connection“.

Hibernate Code Generation

– In “Exporter” tab, select what you want to generate, Model , mapping file (hbm) , DAO, annotation code and etc.

Hibernate Code Generation

See result

Hibernate Code Generation
Note
The generated Hibernate mapping file and annotations code are very clean, standard and easy to modify. Try explore more features.

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
saideep puppala
Guest
saideep puppala

Thank so much…
i am able to generate pojo classes but, in that pojo classes annotations are not generating

Hicham
Guest
Hicham

I had also this problem.
To solve it, check the “Generate EJB3 annotations” in the “Exporter” tab, in the Hibernate code generation window.

Omar
Guest
Omar

Hola, Cuando intento realizar la conexión muestra el siguiente mensaje: “org.hibernate.eclipse.console
Error
Mon Feb 26 18:13:18 CST 2018
org.jboss.tools.hibernate.runtime.spi.HibernateException: org.hibernate.mapping.Column(DUMMY) already exists in SYS.DUAL

org.jboss.tools.hibernate.runtime.spi.HibernateException: org.hibernate.mapping.Column(DUMMY) already exists in SYS.DUAL
at org.hibernate.eclipse.console.workbench.LazyDatabaseSchemaWorkbenchAdapter$2.execute(LazyDatabaseSchemaWorkbenchAdapter.java:141)
at org.hibernate.console.execution.DefaultExecutionContext.execute(DefaultExecutionContext.java:63)
at org.hibernate.console.ConsoleConfiguration.execute(ConsoleConfiguration.java:107)
at org.hibernate.eclipse.console.workbench.LazyDatabaseSchemaWorkbenchAdapter.readDatabaseSchema(LazyDatabaseSchemaWorkbenchAdapter.java:124)
at org.hibernate.eclipse.console.workbench.LazyDatabaseSchemaWorkbenchAdapter.getChildren(LazyDatabaseSchemaWorkbenchAdapter.java:64)
at org.hibernate.eclipse.console.workbench.BasicWorkbenchAdapter.fetchDeferredChildren(BasicWorkbenchAdapter.java:104)
at org.eclipse.ui.progress.DeferredTreeContentManager$1.run(DeferredTreeContentManager.java:232)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:56)”

Alguien me puede ayudar.

Saludos.

Omar
Guest
Omar

Lo pude resolver utilizando una versión de Hibernate inferior. Saludos!!

Alina Alam
Guest
Alina Alam
FIX: FETCHING CHILDREN FROM DATABASE DOESN’T RETURN ANY TABLES There are a lot of people who are complaining about not getting any tables even when hibernate doesn’t generate any error! The first time I followed this tutorial, everything worked perfectly and I didn’t have to do anything different. Later after a month, when I started working on another project, i got this result even though i was doing everything the same way I had done before (eclipse was just being eclipse) So, solution: 1) In the generated hibernate.cfg.xml, change: dbname to DBNAME **you’ll have to write your default schema in… Read more »
Paul Newell
Guest
Paul Newell

Thank you Mkyong for your examples – of much help and expedite the dev process.

luke
Guest
luke

It really helped me, thanks a lot !

Savani
Guest
Savani

I don’t want to create .hbm files any more, I want all model classes with annotations on that. How we can do that? Please guide soonest possible.

Rahul Wagh
Guest
Rahul Wagh

Nice article on the Hibernate setup.

For setting hibernate without using Hibernate eclipse tool you can refer to following link.

This is just alternate if you do not have the Hibernate eclipse tool with you…

http://techpost360.blogspot.in/2015/07/configuring-hibernate-with-java.html

Just post your comments

Geoffrey Stanley
Guest
Geoffrey Stanley

How would you configure your reverse engineering to let hibernate know what you “CREATED_DATE” column would be automatically generated by the database. Such as in postgresql a column that has a default value of current_timestamp?

Er. JK Jha
Guest
Er. JK Jha

good.. worked for me smoothly

Shailendra Gatade
Guest
Shailendra Gatade

MkYong,

Using Eclipse and JBoss Hibernate tools. When I generate the POJO’s from DB (Rev. Engg), I am getting basic data types instead of Entity.

e.g. It generates the following
private Integer application;
instead of
private Application application;

All the required FK’s are in place, am using Java 5 Syntax. Note: I am also not able to see these relations in the Hibernate Configurations view.

Can you please advise???

Thanks and regards,

Shailendra

rohith
Guest
rohith

Hi.. thank you very much for this article.. it helped me a lot..

If anyone out there is using PostgreSQL and not seeing the class files generated, here is a tip.. convert your table names into all lower case. All my tables names were in upper case and when I ran it, no class files were being generated. It drove me crazy for a while and with some dumb luck, I finally realized that PostgreSQLHibernate tools requires the table names to be in lowercase.

Marcos Motta
Guest
Marcos Motta
Hello, I’m trying to do this tutorial using Oracle 10g XE and SQL Server 2008, but I don’t get the list of tables from my database, I’m getting from all databases. When I tried with SQL Server 2008 I’m getting tree databases on Hibernate Configurations: SQL Server – Hibernate Configuration Session Factory Database CDP.Information_Schema CDP.dbo CDP.sys And this message when I execute the “Hibernate Code Generation Configuration…” > Run: org.hibernate.cfg.JDBCBinderException: Duplicate class name ‘CheckConstraints’ generated for ‘org.hibernate.mapping.Table(CDP.sys.check_constraints)’. Same name where generated for ‘org.hibernate.mapping.Table(CDP.sys.check_constraints)’ Duplicate class name ‘CheckConstraints’ generated for ‘org.hibernate.mapping.Table(CDP.sys.check_constraints)’. Same name where generated for ‘org.hibernate.mapping.Table(CDP.sys.check_constraints)’ My question is “How… Read more »
altug
Guest
altug

how can u fix this program i have same

oyoyo
Guest
oyoyo

Great tutorial. Thank you!

trackback
Deb's Desk – Maven 3 + Hibernate 3.6 + Oracle 11g Example (XML Mapping)

[…] Note You may interest read this article – Eclipse + Hibernate tools to generate Hibernate mapping files automatically. […]

Alok
Guest
Alok

how can we change target JDK for hibernate tool manually (without using hibernate perspective window)?

Mahantesh
Guest
Mahantesh

when i tried to generate annotations using reverse engineering from JDBC connection,It just keep saying “Fetching children from Database” till 57%,.it doesn’t progress further.
Can you figure out what is going wrong ?I did all the steps you mentioned but at generation part it is struck!

Vamshi Banda
Guest
Vamshi Banda

did you get solution for your issue? i am using Mysql and I am getting the same error

Hasan
Guest
Hasan

Hi,
I have a database in mssql. One of this tables is “dbo.city” and the other one is “dbo._city”. I try to generate classes but i have a duplication problem. I think it’s about name strategy.
“dbo.city” and “dbo._city” generated with same class name.
Can you help me?
Thanks

Yusuf
Guest
Yusuf

how to configure db setting? i want to use postgresql, how i can add postgresql database driver?

DrakoFire
Guest
DrakoFire

Hi mkyong, nice tutorial! good job, I have a question, if I have my tables with the prefix “namewebapp_” in my database, but the Hibernate Tools generates NamewebappAnybean (obviously), for example: I have a table with name “namewebapp_customers”, the Hibernate Tools generates my JavaBeans with the NamewebappCustomers class name , but I want the name for my JavaBean be only Customers, Is there any configuration to do this?

Regards!

shivarul
Guest
shivarul

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
The method getCurrentSession() is undefined for the type SessionFactory

at com.person.testperson.main(testperson.java:18)

getting this error wht to do tel me :)

regards
shivarul

mintu
Guest
mintu

how i can set perspective for hibernate
because that not showing hibernate code generation configuration in my eclipse
thanks

vj
Guest
vj

i followed the steps you said, but while trying to generate mapping files and pojo classses it is throwing an exception org.hibernate.cfg.jdbcbinder Exception and it says Duplicate class name ‘Syscatalog’ generated for ‘org.hibernate.mapping.Table(SYS.SYSCATALOG_)’. Same name where generated for org.hibernate.mapping.Table(SYS.SYSCATALOG_)

Akin
Guest
Akin

did you get a fix?

Freddie
Guest
Freddie

I have the same problem, any idea?

Radek
Guest
Radek

Hi,

I am following this tutorial but the Hibernate Configuration does not open the table list in the Database item and no error is appear in console. I have tried connect to database with Database Development persitance in Eclipse and it works with my configuration and I have got the list of tables. I am using postgresql driver and create simple Java Project. Do have some advice?

kaanchanha
Guest
kaanchanha

very much explanatory . thanks a lot !!!

mohsin azeem
Guest
mohsin azeem

hey mkyong i like your web so much i also like your way of solving a problem… greate thumbs up!!
my Question is that.
1. if i have added new table to DB how can i create pojo class for single table ? by hibernate tool
2. if i change any column’s property or add new column to table how can i change it in POJO class automatically
THANKS :)

Jeremy
Guest
Jeremy

The “hibernate.default_schema” value HAS to be all uppercase or else you will never be able to connect to the database and there will be no errors as to why (Even though the ‘Test Connection’ is successful). Took me a long time to find that out, so I’m posting it here in case someone needs the solution.

Anderson
Guest
Anderson

Thanks, before your tip I couldn’t see the table list.

Khanh
Guest
Khanh

Thank you very much:))

Nicks
Guest
Nicks

Thanks for this comment, even i spent a lot of time for this

trackback
Maven 3 + Hibernate 3.6 + Oracle 11g Example (XML Mapping)
[…] File : DBUser.java package com.mkyong.user;   import java.util.Date;   /** * Dbuser generated by hbm2java */ public class DBUser implements java.io.Serializable {   private int userId; private String username; private String createdBy; private Date createdDate;   public DBUser() { }   public DBUser(int userId, String username, String createdBy, Date createdDate) { this.userId = userId; this.username = username; this.createdBy = createdBy; this.createdDate = createdDate; }   public int getUserId() { return this.userId; }   public void setUserId(int userId) { this.userId = userId; }   public String getUsername() { return this.username; }   public void setUsername(String username) { this.username = username;… Read more »
mathaker
Guest
mathaker

Sir,

I am learning hibernate. I have tried your tutorial in both Eclipse and NB.
I just have two question.
Q-1. As you said NB is slow, can you tell us how?
Q-2. If I add one more column in DBUser table, will it reflect automatically in hbm file and pojo? If not then I have to change mannually.

Prasad Isuru
Guest
Prasad Isuru

Thank You sir,Your all posts very use full …

srinivas pamula
Guest
srinivas pamula

Hi sir, i am watching ur wesite,
which is helping me a lot.
thank u sir.