Generate Java POJO and Hibernate XML from database tables

Today we have frameworks to persist java objects to database without writing DAO's and hibernate is one which is widely used. But for nascent developers, creating its mapping to database tables is still difficult.

Recently I come across a way to generate Java  POJO and hibernate mapping XML  from database tables  using a Jboss Hibernate Tools. Its as easy as a click  and magic, mapping XML is generated and
corresponding POJO 's are generated. Listed down the steps :-

1. Install the hibernate-tools jar using Eclipse's Install New software, selecting URL from
http://www.jboss.org/tools/download.html depending upon the eclipse version.

2. Click on [File -> New -> Other -> Hibernate -> Hibernate Configuration File] and create a cfg file. The following properties should be specified : jdbc url , username, password, DB schema, driver class and dialect.

3. Click on [File -> New -> Other -> Hibernate -> Hibernate Console Configuration ] and create a new console configuration. Add the jar file that contains your DB driver in the classpath section at the bottom.

4. Enter the name of the console configuration. Click Browse button against the Configuration file and select the cfg.xml file created in step 3

5. Click on [File -> New -> Other -> Hibernate -> Hibernate Reverse Engineering File(reveng.xml) and select the location of the file.

6. Select the cfg.xml file created in step 3 as the Console Configuration. Click on include button and specify the schema and table name(s) to reverse engineer. Multiple table names can be specified using sql wild char (eg: TBL_%). Click Finish

7. Switch to the Hibernate perspective and Click on the Hibernate icon in the tool bar and select the [Hibernate Code Generation ..] option.

8. Right click on the [Hibernate Code Generation]tree node and select New.

9. Give the name of the configuration and select the console configuration created in step 5 and reveng.xml created in step6-7. Also select the Output Directory and a relevant package.

10. Go to the Exporters tab and check Generate domain code(.java) and Generate mappings (hbm.xml). Click run.

11. The hibernate mapping xml files and Java classes will be created in the output directory specified in step 9.

Comments

Popular posts from this blog

When to use getClass() and instanceOf in Java

How class.forName loads the Database Driver in JDBC

Why Time gets truncated with ResutSet getDate() function.