Wednesday, January 05, 2011

Introducing Hibernate In Java Using NetBeans

In one of my recent posts, I introduced the theoretical topic of Object-Relational Mapping (ORM) - http://gautam-m.blogspot.com/2010/11/object-relation-mapping.html. In this post I am going to take a step forward and introduce Hibernate - an open source Java persistence framework from JBoss.

This post covers four basic principles of Hibernate -

  • Configuring a Java project for Hibernate
  • Inserting data using Object Persistence
  • Retrieving data using Hibernate Query Language (HQL)
  • Changing the database configuration to connect to another DBMS

Though the post and screen-shots emphasize on NetBeans, the concept is the same for all IDEs. Hibernate configuration files can definitely be written without an IDE but make sure all the required class libraries are properly referenced.

Requirements to run the example in the article - NetBeans, MySQL, JavaDB, Java and Hibernate. Java can be downloaded here, installing the All NetBeans package will cover JavaDB and Hibernate. and MySQL can be downloaded here.

Configuring a Java project for Hibernate

The crux of Hibernate is the creation and usage of configuration files. There are three types of configuration files which are to be setup for Hibernate -

  1. The .cfg.xml file - this is the main configuration file which contains information about the database like the database URL, the driver, the username and password, etc. Hibernate can optimize it's behavior depending on the DBMS being used. To facilitate this, a property called Dialect is specified. However this is an optional property as Hibernate can deduce this depending on the JDBC metadata returned by the driver
  2. The .reveng.xml file - this file holds the data corresponding to the schemas and tables being utilized by Hibernate in the application
  3. The .hbm.xml - these files maps POJOs (Plain Old Java Objects) to the table schemas of the database

Typically one .cfg.xml and one .reveng.xml exist for a project and one .hbm.xml exists for each table (mapped to a class). The .hbm.xml maps the object properties to the table columns. It is possible to add new properties to the class which have no effect on the backend tables.

To create these files in a NetBeans project, select New File and select the following File Types from the Hibernate category -

  1. Hibernate Configuration Wizard
  2. Hibernate Reverse Engineering Wizard
  3. Hibernate Mapping Files and POJOs from Database

Follow the wizards to complete the configuration setup. I used MySQL and JavaDB as my DBMS to create a sample application to insert and retrieve data. You can get the MySQL and JavaDB scripts along with the NetBeans project here.

Inserting data using Object Persistence

Inserting data is a cake-walk in Hibernate. All that is there to do is to create the object and store the object data in the database tables using the save method of a SessionFactory object. The following piece of code persists the object data -

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();

// Create the object
session.save(object);

Retrieving data using Hibernate Query Language (HQL)

Retrieving data is done through a query language designed for Hibernate called the Hibernate Query Language. HQL is a Object-Oriented Query Language and is very much similar to the traditional SQL we use. The beauty of HQL is that the result of the query is returned as a list of objects rather than as a ResultSet. These objects can be used directly in the code without any overheads. HQL is very wide topic, so I am going to skip the details here but there are several tutorials available for HQL on the Internet. The createQuery method of the above Session object is used along with the list method of the Query object to get the objects -

Query query = session.createQuery(queryString);
for (Object object : query.list()) {
// cast and use the object appropriately
}

Changing the database configuration to connect to another DBMS

The best feature of Hibernate according to me is it's ability to change a DBMS without any change to the application code. To change the DBMS, open the Hibernate Configuration File (typically hibernate.cfg.xml) and change the dialect, driver class, connection URL, username and password to the values corresponding to the new DBMS.

These changes can be done either through the design view or directly on the XML.

23 comments:

Chandu said...

please tell me how to use SQlite with hibernate on netbeans

Anonymous said...

I am getting an error in SessionFactory sessionFactory =
new Configuration().configure().buildSessionFactory();

it says Configuration cannot be instantiated

tony said...

This blog contain excellent stuff. Hyderabadsys provide Hibernate Online Training.For more visit this link HIBERNATE Online Training

tony said...

Nice article.We are providing Hibernate Online Training.HIBERNATE Online Training

tony said...

Nice article.We are providing Hibernate Online Training.For more visit HIBERNATE Online Training

neelmani said...

if u are getting error in SessionFactory sf=new Configuration().configure().buildSessionFactory();

then either you have to specify name and path of yuor configuration file in configure(" ");

or you have not import its related package.

Unknown said...

wow...nice article.Thanks for sharing this great source full of Hibernaterelated posts.realy great work onece again thanks me and Ithubonlinetraining.

Unknown said...

I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly.
Hibernate Online Training in USA

Unknown said...


There are lots of information about latest technology and how to get trained in them, like Best hibernate Online Training in Hyderabad in Hyderabad have spread around the web, but this is a unique one according to me. The strategy you have updated here will make me to get trained in future technologies hibernate Online Training in Hyderabad By the way you are running a great blog. Thanks for sharing this blogs..

Unknown said...

There are lots of information about latest technology and how to get trained in them, like Best Hibernate Offline Training in Hyderabad

Murali Rajesh said...

Hibernate and spring are the frameworks of Java. A java developer should be well aware of these frameworks in order to master the technology and work efficeiently.
spring training in chennai | hibernate training in chennai
FITA Academy reviews

Unknown said...

Java is the most robust secured and multi threaded programming language which is the reason why most the the developers go for java. A single java code can be used for various platforms.
JAVA training in chennai | java training institutes in chennai | FITA Academy Chennai

Unknown said...

Simple CRUD with JSF and Hibernate - GeekOnJava:


Hibernate CRUD example using HQL query language:


Solve QuerySyntaxException in Hibetnate:

navya said...

I have read your blog its very attractive and impressive. I like it your blog.

.Net Training in Chennai | .Net Online Training | Dot Net Training in Chennai

Dot Net Online Training | LINQ Online Training

Unknown said...

nice ans useful blog to read

java j2ee training course contents | java j2ee training institutes in chennai | java j2ee training | java training in chennai velachery

Unknown said...

Hibernate framework simplifies the development of java application to interact with the database. Hibernate is an open source, lightweight, ORM (Object Relational Mapping) tool.
Thanks a lot! You made a new blog entry to answer my question; I really appreciate your time and effort.
java training in chennai |
java training institutes in chennai

Unknown said...

Much obliged to you for sharing this magnificent blog. It will enhance my insight about JAVA systems. This blog will find out about JAVA ideas. Likewise, it will enhance my programming ability.
Spring Hibernate Training | Spring and Hibernate Training in Chennai | Spring framework Training in Chennai | Spring course in Chennai

beryltryphosa said...

snowflake interview questions
riya sold her car
zensoft interview questions
top 10 political websites
difference between vb and vb.net

24*7WP said...

247wpsupport is best organization for website maintenance and help .if you are business owner and using WordPress and facing any kind of issue related WordPress to handle your website contact WordPress Customer Service at 1 (844) 589 2165
Hi there, First of all great post enjoyed reading and taking note of your worthwhile information! This is one of your best posts to date! I really appreciate that you added links to further reading to document and support your points.
WordPress Customer Service
WordPress Help

24*7WP said...

Hi there, First of all great post enjoyed reading and taking note of your worthwhile information! This is one of your best posts to date! I really appreciate that you added links to further reading to document and support your points.
WordPress Phone Number

APTRON said...

Hibernate Interview Questions and Answers

vral times said...

Great deal! I actually sent it with a decorator who did a little homework. Nor can it be denied that he gave me food because I found it for him ... haha. So grant me to fix up this.... Appreciative to YOU for the supper!! Thinking about everything, to be sure, thanx so that contributing energy might see this point here on your site.
Visit viral times for tech news.

Amit kumar said...

Waoo This article is so amazing technically.
Here all content so useful and helpful for beginner and experience both.This site is so amazing, This sites gives good knowledge of hibernate ,This is very helpful for me.