Tuesday, May 21, 2013

Hibernate(Object Relational Mapping) and working of hibernate


Hibernate:

Hibernate is one of the commonly used ORM tool to deal with database. Hibernate is a framework (software) to be used in applications that deals with database. 

What is ORM:

ORM refers to Object Relational Mapping i.e, Mapping the java objects with the corresponding relational records in the database.

Advantages over jdbc:

As we have jdbc to deal with database,but  hibernate will have more advantages than jdbc.

--> Use of hibernate will improve the productivity (less amount of code compared to jdbc)

--> Hibernate provides relations like one to one , one to many, many to one and many to many

-->  Hibernate comes with HQL ( hibernate query language), which is database independent. So we can deal with any database without changing the code.

--> If we use hibernate, no need to configure connection pool (c3p connection pool will be bundled with hibernate)

--> Hibernate supports two levels of cache (first level and second level) which improves the performance of the application.

--> In hibernate , exceptions that occur are unchecked exceptions where as in jdbc , checked exceptions will be caught and thrown by try catch.

Note:

According to the hibernate documentation, hibernate may not be the best solution for data centric applications which uses stored procedures for buisiness logic. 

Hibernate gives best result for the applications which have buisiness logic as part of java classes instead of stored procedures.


Hibernate Architecture:


As shown pictorially, java application with hibernate api code will communicate with hibernate software which will connect to the database.

Components of Hibernate:

Hibernate mainly consists of three components. They are

--> Hibernate configuration file

--> Hibernate mapping file

--> Pojo classes

Hibernate Configuration file:

A configuration file is an xml file contains the configuration details like driver class name, url, user name and password to connect with database. It also includes the mapping file information

syntax:


A hibernate application contains one configuration file with one or more mapping (hbm) files.

Hibernate mapping file: 

A mapping file (hbm) shows which table is mapped with which pojo class, and mapping the properties of pojo classes with columns of tables.

syntax: 


A Hibernate application can have one or more mapping files. We can map multiple pojo classes with tables by using <class> .

It's recommended to write seperate hbm (mapping) files for each table and pojo class.

Number of mapping files, pojo classes depends on number of tables in the database.

Pojo class:

A POJO (plain old java object) is a normal java bean with couple of setters, getters and/ or some additional methods.

syntax: 



Sample Hibernate application:

Create a java project HibernateSampleApp , add the hibernate capabilities( hibernate jar's ) to the project build path and as discussed earlier we need to have the following files.

A Hibernate Configuration file.




and Hibernate mapping file Student.hbm.xml


and a pojo class Student.java


Now create a main class SampleHibernateApp with main()



If we run the above application, we can found a table with name student in database with columns id, student_name.

As we have defined an extra property in hibernate.cfg.xml, hbm2ddl.auto will create the tables if not exists.

If it's values is update it will update the table if already exists , otherwise it will create the table in database.

show_sql property will show  the query sent to the database in console.


What's happening when we run the application:

When we run the SampleHibernateApp, hibernate will start execution by creating a Configuration object. Immediately hibernate software will call configure() which is an expensive method.

when configure() got called, hibernate will load the configuration file (hibernate.cfg.xml) into jvm's memory and will check for the properties mentioned.

 As we have defined mapping file information in configuration file, hibernate will also loads the mapping file into jvm memory and checks for the appropriate tables in database. If not exists, if we have given hbm2ddl.auto property, hibernate will create the required tables.

So calling configure() takes so much of time to do all these tasks. That's why hibernate specification says we should call configure() only once through out the life time of a project.

Once we have configuration object we can get SessionFactory object by using buildSessionFactory().

When buildSessionFactory() called, hibernate will try to connect with database with the information already stored in jvm memory ( from cfg and hbm files) and will create some basic queries for inserting, updating, deleting and retrieving and stores those queries in jvm memory.

buildSessionFactory() is also an expensive method since lot of task is going behind. We should call this only once through out the project.

A SessionFactory is an interface which can hold a bunch of Session objects.
Once we got SessionFactory we can get session object by calling openSession() which will get's the connection from database.

beginTransaction() will enable the transactions with database.

When we create object to our pojo class Student, the instance variables were initialised with default values initially (0 for int, null for string /advanced data types).

Calling setters will assign the values that we specified to the student object.

Calling session.save() will not send an insert query to the database. The student object will be associated with session object when we call save(). 

When we call commit() hibernate will check in the first level cache ( which will be created at the time of creating session object ) whether any object is associated (attached) to the session object with some code and will get the class name from object (student.getClass()).

 As hibernate already read the cfg,hbm files and stored in jvm, from that information it will get the table to which it has to send the query.

Finally , hibernate will picks the insert query that was already stored in jvm memory based on some internal registration code and will send that query to the database.

We should close the session so that the connection from the database will be given back.

Note:

Using hibernate in web based applications along with spring explained here


2 comments: