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) - 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;

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.


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

Innovapath said...

Excellent Post. Also Visit

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.

John Mcclane said...

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

Harini Manyam 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

Harini Manyam 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..

Harini Manyam 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

Raghu Sharma 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

Sushil Das said...

Simple CRUD with JSF and Hibernate - GeekOnJava:

Hibernate CRUD example using HQL query language:

Solve QuerySyntaxException in Hibetnate:

Devi.Angularjs said...

Interesting Article

Spring Hibernate Online Training | Hibernate Training in Chennai

Hibernate Online Training | Java Online Training | Java EE Online Training

Naviya Nair 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

John Alert said...

Hibernate Online Training Hibernate Online Training Hibernate Training in Chennai Hibernate Training in Chennai Java Online Training Java Online Training

Hibernate Training Institutes in ChennaiHibernate Training Institutes in Chennai Java Online Training Java Online Training

Rajapriya R 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

Nitesh Kumar said...

I really appreciate information shared above. It’s of great help. If someone want to learn Online (Virtual) instructor lead live training in Netbeans, kindly contact us
MaxMunus Offer World Class Virtual Instructor led training on Netbeans. We have industry expert trainer. We provide Training Material and Software Support. MaxMunus has successfully conducted 100000+ trainings in India, USA, UK, Australlia, Switzerland, Qatar, Saudi Arabia, Bangladesh, Bahrain and UAE etc.
For Demo Contact us.
Nitesh Kumar
Skype id: nitesh_maxmunus
Ph:(+91) 8553912023

preethi s 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

harry lopiz said...

The blog or and best that is extremely useful to keep I can share the ideas of the future as this is really what I was looking for, I am very comfortable and pleased to come here. Thank you very much.
Gamesunblocked Unblockedgamesbeast unblockedgames77atschool