Wednesday, October 04, 2006

Hibernate Framework for JAVA

Now a days Object Oriented approach is the most popular. No doubt! But no doubt we need to deal with the database which is mostly based on Relational model. So definitely while building an application that requires interacting with database, the interaction becomes complex when your application is Object Oriented and the database is relational. The complexity in this case arises due to the knots and knaves of cross approach communication.

So when such a need arises where need to make you object orinented application communicate with the relational database, we need a mediator which can make the objects of two different orientations (object oriented and relational) talk to each other. One such good example of this is the Java Database Connectivity (JDBC) API. JDBC allows you to access different databases without much difficulty. But as JDBC is relatively a low level API and provides a low level of abstraction, it can be relied on for the medium or low level projects but for the enterprise level projects. For enterprise level big application, what is more suited is a framework which acts a medisator facilitating the interaction of the objects of Object oriented approach and releational appraoach. Such frameworks ar ecalled Object Relational Mapping (ORM).

Object Relational Mapping:
The process of transformation from a relational approach to an object oriented approach is known as Object Relational Mapping. The Hibernate framework is an ORM : The best example of an ORM framework for Java is Hibernate. But before going further, I would assume that my readers are familier with the object oriented and releational modles :-)

Introduction to Hibernate:

As of now I have made it probabaly clear that what is the need of ORM. ORM reduces our (developer's) task by takig care of how the releational oriented objects will work while working with classes. Although there are various differnet frameworks available in this category, but Hibernate is comparitively simpler and flexible than all others.

Prerequisites to Make Your Application Hibernate Enabled: Following are the three prerequisites to make your web application hibernate enables:

1. Persistence Class: A class is persistent when it is based on the Plain Old Java Object or POJO model. A persistent class is one which has instance variables and getter and setter methods to get and set the variable values. The main function of a persistent class in Hiberation is to to act as a blueprint of the tables in the database with which your web application interacts. So each tables of the database dores have a corresponding class in you application. The instance variables of the class coresponds to the various cloumns of the table. The data-type of the instance variables depend on the data-type of the columns. For example, if there is a column in a particular table in your database whose datatype is varchar(20), the intance variable corresponding to this variable in the blueprint class of the corresponding class will be Stirng. Now guess what each object of this persistence class will represent. Yes you guessed it right, each object of this class will represent a touple (row) in the corresponding table.

Now as we said each tables in the database, will have a corresponding persistence class in your web application, how will the application come to know which class corresponds to which table ? This mapping is mentioned in an XML file called Mapping file.

2. Mapping file: The mapping file contains detailed mapping between the persistence class and the table it represents. The following are the various required attributes of the XML file:

a. Root Element: The root element enclosing all other elements should be hibernate-mapping.
b. Child Elements class: The child elemets of root should be class. The class element, as the name itself indicates is used to map the various persistent classes to the corresponding table names. This element has two attributes. The first attribute is "name", the value of which is the name of a class to be mapped. The name of the class is the fuly qualified name of the class. By fully qualified I mean that the class name should contain the package name also. The second attribute is "table", the value of which specifies the name of the table which the class represents or is a blueprint of. For example, lets assume that u have a persistent class having fully qualified name as "com.myproject.persistent.Entity" which needs to be mapped to the a table named ENTITY, then the class element will be as follows:

<class name="com.myproject.persistent.Entity" table="ORDERS"></class>

Now a table has various columns and the corresponding persistent class has same number of instance variables. So how does the appilication knows which instance variable represents which column ? This mapping is defined by the element property.

c. property: The property element is used to map the varuious columns in a tables to the corresponding instance variables. This element has an attribute named "name" the value of which species the name of the instance variable in the corresponding persistent class which needs to be mapped to a particular column of the table. The name of the column is defined by a child element of this elment named "column". The child element column has an attribute named "name" which specifies the name of the column to which the instance variable is mapped. There are other two attributes of the column element named "length" and and "sql-type" which specify th length and sql-type of the column which is being mapped tothe corresponding instance variable. For example look at the following configuration of the mapping file:

<property name="entityname">
<column name="entityname" sql-type="char(255)" not-null="true"/>

The above configuration maps an instance variable named "entityname" to a column named "entityname" whose type is char(255).

Now as we know that the primary key always has a special place in a table, so the primary key of the table is mapped using a special element called id.

c. Child Element id: This element is also defined same as the property element. The only differnce lies in the fact that it also contains an extra child element "generator". This element is used to specify if the primary key value can be automatically generated or not. This is specified using an attribute named "class". If the value of the class attribute is "assigned" it tells Hibernate that the application would be used to assign the primarykey vales instaead of auto generating. For example look at the following configuration of the mapping file:

<id name="entityid" type="int" unsaved-value="0">
<column name="entityid" sql-type="integer(2)" not-null="true"/>
<generator class="assigned"/>

The above configuration tells Hibernate that the name of the primary key is "entityid" and that the type of the column is integer(2) which is mapped to the instance variable "entityid" of the persistence class which is mapped to the instance variable "entityid" of datatype "int". The value "assigned" of the class attribute of the child element generator specifies that the application itself will provide the value of the primary key and therefore it is not auto generated.
So finally if you look at the Mapping File for a persistent class called Entity for a table called entity having two column entityid and date, it would look something like this:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN"";
<hibernate-mapping default-cascade="none" default-access="property" auto-import="true">
<class name=" com.myproject.persistent.Entity" table="entity" mutable="true" select- before-update="false" optimistic-lock="version">
<id name="entityid" type="int" unsaved-value="null">
<column name="entityid" sql-type="integer(2)" not-null="true" />
<generator class="assigned" />
<property name="date" not-null="false" >
<column name="date" sql-type="datetime" not-null="true" />

The name of the above mapping file is Entity.hbm.xml. All the configuration files are named as .hbm.xml. Now all set and done, we need an entry point to Hibernate enabled application. For this we need an Hibernate Configuration file.

3. Hibernate Configuration file: This file contains the configuration that is required for communication with the underlying database. This file also declares all the mapping files being used by your web application. The root element of this configuration XML file is name as "hibernate-configuration". Following are the two importent elements that are present in this configuration file:

a. property: This element is used to configure various parameters called property parameters, such as the database server type (MySQL, Oracle, PGSQL etc), database URL, username/password to be used to connect to the database, dialect class, etc. All these parameters are defined using the name attribute of the property element. For example, look at the following configuration of the Hibernate Configuration file:

<!-- Database connection settings -->
<property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:data/tutorial</property>
<property name="connection.username">sanjeev</property>
<property name="connection.password">qwedsa</property>

b. mapping: The mapping element of the Hibernate Configuration file is used to declare all the the mapping (hbm ) files. This element has an attribute named "resource" the value of which specifies the path of the hbm file. For example, look at the following configuration of the Hibernate Configuration file:

So the Hibernate Configuration file for a web application where you are using Oracle database, with username scott and password tiger with one connection at a time, the file would look something like this:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN"";
<!-- Database connection settings -->
<property name="connection.driver_class"> oracle.jdbc.driver.OracleDriver </property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl </property>
<property name="connection.username">scott</property>
<property name="connection.password">tiger</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect"> org.hibernate.dialect.OracleDialect </property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<mapping resource=" com/someorg/persist/Event.hbm.xml"/></session-factory>

So this is it !! To get started with hibernate. I personally feel that the concept of Hibernate is not that tough but using it is a bit tricky as you should design your application in sucha a way that you can use Hibernate easily. In the next post releating to hibernate, I will try to give you an idea about how to use Hibernate in real world.

Till then Happy Reading and Happy Programming :-)


Anonymous said...

Nice Articles...Gives knowledge about Latest technologies in java

Anonymous said...

Good Article...Sanjeev i would suggest that if u can put couple of points regarding the location of config and mapping files in context with web application directory structure then tht wuld be really more informative for beginners...

Anonymous said...

compare car insurance rate
cheap car insurance quote uk
car insurance houston
cheapest car insurance
car insurance n
discount car insurance
teen car insurance
car insurance group
state farm car insurance
direct line car insurance
aig car insurance
car insurance estimate
admiral car insurance
car insurance for woman
best car insurance company
best car insurance quote
online car insurance rate
best car insurance quote
online car insurance rate
state farm car insurance
state farm car insurance
car insurance policy
instant car insurance quote
usaa car insurance
geico car insurance quote
car insurance rate
car insurance quote
mercury car insurance
auto insurance quote
progressive car insurance

Random Keyword: :)
cheap car insurance quote

Anonymous said...

Thanks for your wonderful blog. I've learned alot about insurance consultant
here. I've got a little site which contains info about insurance consultant , as well
as a few other things. Please stop by

Anonymous said...

relax and enjoy

Anonymous said...

tune khud bhi pada kya ye sab :)

Anonymous said...

wi lake
new home sales professional
property sale
premium term insurance
health insurance companies list
michigan unemployment insurance agency
sales tax new car
insurance agent
as is auto bill of sale

Michael said...

Young Fatties