codetoad.com
  ASP Shopping CartForum & BBS
  - all for $20 from CodeToad Plus!
  
  Home || ASP | ASP.Net | C++/C# | DHTML | HTML | Java | Javascript | Perl | VB | XML || CodeToad Plus! || Forums || RAM 
Search Site:



Home » JAVA » Article

Understanding Hibernate ORM for Java/J2EE

Article by: Saritha.S.V (6/29/2005)
Bookmark us now! Add to Favourites
Email a friend! Tell a friend
Summary: Hibernate is the most popular and most complete open source object/relational mapping solution for Java environments.Hibernate's goal is to relieve the developer from 95 percent of common data persistence related programming tasks.
Viewed: 82576 times Rating (265 votes): 
 2.6 out of 5
  Rate this Article   Read Comments   Post Comments

Understanding Hibernate ORM for Java/J2EE



Understanding Hibernate Object/Relational mapping Solution

An article by Saritha.S.V


Introduction

As you all know in today's enterprise environments working with object-oriented software and a relational database can be cumbersome and time consuming. Typically in an enterprise application if you are passing objects around and sometimes reach the point where you want to persist them, you will open a JDBC connection, create an SQL statement and copy all your property values over to the PreparedStatement or into the SQL string you are building. This may be easy for a small value object - but for an object with many properties , you may face many difficulties . As myself have experienced and most of you , Java Programmers have seen , the object-relational gap quickly becomes very wide if you have large object models .Thus the activities involved in persisting data are tedious and error-prone . So we go for Object-relational mapping (O/R mapping) which is a common requirement of many software development projects.

If you are working with object-orientated programming and relational databases, you will surely have noticed that these are two different paradigms. The relational model deals with relations,tuples and sets - it is very mathematical by nature. The object-orientated paradigm however deals with objects, their atributes and associations to each other. As soon as you want to make objects persistent using a relational database you will notice: There is a rift between these two paradigms, the so called object-relational gap. A object-relational mapper ( ORM ) will help you bridge that gap.
If we also take into consideration the inevitable change of requirements, we're in serious trouble: the data storage structure must be kept in sync with the source code. Using ORM we can make the application portable to all databases .

Why ORM ?

The term object/relational mapping (ORM) refers to the technique of mapping a data representation from an object model to a relational data model with a SQL-based schema. So what can an ORM do for you? A ORM basically intends to takes most of that burden of your shoulder. With a good ORM, you have to define the way you map your classes to tables once - which property maps to which column, which class to which table, etc.
With a good ORM you can take the plain java objects you use in the application and tell the ORM to persist them. This will automatically generate all the SQL needed to store the object. An ORM allows you to load your objects just as easily: A good ORM will feature a query language too. The main features include :

1. Less error-prone code
2. Optimized performance all the time
3. Solves portability issues
4. Reduce development time

Hibernate

Hibernate is in my opinion the most popular and most complete open source object/relational mapping solution for Java environments . Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types), but also provides data query and retrieval facilities and can significantly reduce development time , otherwise spent with manual data handling in SQL and JDBC. It manages the database and the mapping between the database and the objects.
Hibernate's goal is to relieve the developer from 95 percent of common data persistence related programming tasks. Hibernate adapts to your development process, no matter if you start with a design from scratch or work with a legacy database.
Hibernate generates SQL for you, relieves you from manual result set handling and object conversion and keeps your application portable to all SQL databases . .Æ’nHibernate allows to store , fetch ,update and delete any kind of objects . Hibernate lets you develop persistent classes following common Java idiom - including association, inheritance, polymorphism, composition and the Java collections framework .

The Hibernate Query Language, designed as a minimal object-oriented extension to SQL, provides an elegant bridge between the object and relational worlds.

Key features include :

1. Integrates elegantly with all popular J2EE application servers , web containers and in standalone applications .
- Hibernate is typically used in Java Swing applications, Java Servlet-based applications, or J2EE applications using EJB session beans

2. Free / open source
- Hibernate is licensed under the LGPL (Lesser GNU PublicLicense).critical component of the JBoss Enterprise Middleware System (JEMS) suite of products

3. Natural programming model
- Hibernate supports natural OO idiom; inheritance, polymorphism, composition and the Java collections framework

5. Extreme scalability
- Hibernate is extremely performant, has a dual-layer cache architecture, and may be used in a cluster

6. The query language
- Hibernate addresses both sides of the problem; not only how to get objects into the database, but also how to get them out again

7. EJB 3.0
- Implements the persistence API and query language defined by EJB 3.0 persistence


What is a Persistent class ?

Hibernate provides transparent persistence, the only requirement for a persistent class is a no-argument constructor . In a persistent class no interfaces have to be implemented and no persistent superclass has to be extended . The Persistent class can be used outside the ¡§persistence¡¨ context .
Persistent classes are classes in an application that implement the entities of the business problem. Let me illustate this with a simple eg : login entity . The persistent class can be like :


Select All Code


Persistent classes have, as the name implies, transient and also persistent instance stored in the database. Hibernate makes use of persistent objects commonly called as POJO (Plain Old Java Object) programming model along with XML mapping documents for persisting objects to the database layer. POJO refers to a normal Java object that does not serve any other special role or implement any special interfaces of any of the Java frameworks like a Java Bean

The ultimate goal

Take advantage of those things that relational databases do well , without leaving the Java language of objects / classes .I will say , the ultimate aim is - Do less work , Happy DBA .

Hibernate architecture

I believe Hibernate provides persistence as a service, rather than as a framework. I will show two common architectures incorporating Hibernate as a persistence layer .
As I have already explained for persisting objects Hibernate makes use of persistent objects commonly called as POJO , along with XML mapping documents .
In Web (two-tiered) Architecture Hibernate may be used to persist JavaBeans used by servlets/JSPs in a Model/View/Controller architecture .
In Enterprise (three-tiered) Architecture Hibernate may be used by a Session EJB that manipulates persistent objects.

Typical Hibernate code


Select All Code


First step in hibernate application is to retrieve Hibernate Session . Hibernate Session is the main runtime interface between a Java application and Hibernate. SessionFactory allows applications to create hibernate session by reading hibernate configuration file hibernate.cfg.xml . After specifying transaction boundaries, application can make use of persistent java objects and use session for persisting to the databases.

Getting Started With Hibernate

1. Download and Install Hibernate
2. Hibernate is available for download at http://www.hibernate.org/
3. Include the hibernate.jar file in the working directory.
4. Place your JDBC driver jar file in the lib directory.
5. Edit hibernate configuration files, specifying values for your database (Hibernate will create a schema automatically)

A Simple Java Application

Here I will show a sample application which I developed which uses Hibernate.

1. Preparing Database

First I created a single table as USER




Select All Code


2. Creating persistent java objects

Following code sample represents a java object structure which represents the User table. Generally these domain objects contain only getters and setters methods.

Source code for User.java


Select All Code


Hibernate works best with the Plain Old Java Objects programming model for persistent classes. Hibernate is not restricted in its usage of property types, all Java JDK types and primitives (like String, char and Date) can be mapped, including classes from the Java collections framework. You can map them as values, collections of values, or associations to other entities. The id is a special property that represents the database identifer (primary key) of that class.


3. Mapping POJO with persistence layer using hibernate mapping document

Each persistent class needs to be mapped with its configuration file. Following code represents Hibernate mapping file for User class.

Source code for User.hbm.xml


Select All Code


Hibernate mapping documents are straight forward. I will describe the major elements in the mapping file.
1. <hibernate-mapping> element
The root element of hibernate mapping document is <hibernate-mapping> element. This element has several optional attributes.

2. <class> element
The <Class> element maps the domain object with corresponding entity in the database. In simple words the <class> element maps a table with corresponding class . <hibernate-mapping> element allows you to nest several persistent <class> mappings, as shown above. It is however good practice to map only a single persistent class in one mapping file and name it after the persistent superclass, e.g. User.hbm.xml

3. <id> element
The <id> element defines the mapping from that property to the primary key column. The <id> element represents the primary key column, and its associated attribute in the domain object. Mapped classes must declare the primary key column of the database table. Most classes will also have a JavaBeans-style property holding the unique identifier of an instance.

4. <generator> element
The optional <generator> child element names a Java class used to generate unique identifiers for instances of the persistent class. If any parameters are required to configure or initialize the generator instance, they are passed using the <param> element .Some commonly used generators are :
1. Increment - generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. Do not use in a cluster.
2. Sequence - uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, or a generator in Interbase. The returned identifier is of type long, short or int
3. Assigned - lets the application to assign an identifier to the object before save() is called. This is the default strategy if no <generator> element is specified.
4. Foreign - uses the identifier of another associated object. Usually used in conjunction with a <one-to-one> primary key association.

5. <property> element
The <property> element declares a persistent, JavaBean style property of the class. The <property> elements represent all other attributes available in the domain object.
typename could be:
1. The name of a Hibernate basic type (eg. integer, string, character, date, timestamp, float, binary, serializable, object, blob).
2. The name of a Java class with a default basic type (eg. int, float, char, java.lang.String, java.util.Date, java.lang.Integer, java.sql.Clob).
3. The name of a serializable Java class.

6. <many-to-one> element
An ordinary association to another persistent class is declared using a many-to-one element. The relational model is a many-to-one association: a foreign key in one table is referencing the primary key column(s) of the target table. A typical many-to-one declaration looks like this:
<many-to-one name="product" class="Product" column="PRODUCT_ID"/>

7. <one-to-one> element
A one-to-one association to another persistent class is declared using a one-to-one element . A typical many-to-one declaration looks like this:
<many-to-one name="product" class="Product" column="PRODUCT_ID"/>

3. Hibernate Configuration File

Hibernate configuration file contains information needed to connect to persistent layer and the linked mapping documents. You can either specify the data source name or JDBC details that are required for hibernate to make JDBC connection to the database.
The element <mapping-resource> refers to the mapping document that contains mapping for domain object and hibernate mapping document.

Source code for hibernate.cfg.xml


Select All Code


Here is how you can use Hibernate in your programs. Typical Hibernate programs begin with configuration that is required for Hibernate. Hibernate can be configured in two ways. Programmatically and Configuration file based. In Configuration file based mode, hibernate looks for configuration file ¡§hibernate.cfg.xml¡¨ in the claspath. Based on the resource mapping provided hibernate creates mapping of tables and domain objects. In the programmatic configuration method, the details such as JDBC connection details and resource mapping details etc are supplied in the program using Configuration API.

An example of programmatic configuration of hibernate


Select All Code


4. Inserting new record

Source code for UserInsertHibernate.java


Select All Code


4. Quering the database

Source code for UserQueryHibernate.java



Select All Code


Hibernate Query Language

Hibernate is equipped with an extremely powerful query language that looks very much like SQL. Queries are case-insensitive, except for names of Java classes and properties.

HQL is a language for talking about ¡§sets of objects¡¨. It unifies relational operations with object models . Make SQL be object oriented . It uses Classes and properties instead of tables and columns . It supports Polymorphism , Associations , Much less verbose than SQL .

Other features include :

1. Full support for relational operations
2. Inner/outer/full joins, cartesian products
3. Projection
4. Aggregation (max, avg) and grouping
5. Ordering
6. Subqueries
7. SQL function calls

Simplest HQL Query:

From User
- Returns all instances of the class User
From User as user, Group as group
- using aliases
-
More realistic example :

Select user.name from User user where user.name like ¡¥mary%¡¦


Alternative Persistence Frameworks


Some other Persistence Frameworks are :

Open Source ones are
OJB
iBATIS
Castor
Commercial ones are
JDO Genie
Jrelay





CodeToad Experts

Can't find the answer?
Our Site experts are answering questions for free in the CodeToad forums
Rate this article:     Poor Excellent
View highlighted Comments
User Comments on 'Understanding Hibernate ORM for Java/J2EE'
RELATED ARTICLES
Java MP3 Player
by David Barron
A fully functioning MP3 Player with complete source code available for download
A simple way to JTable
by Kanad Deshpande
Many face trouble while dealing with JTable. Here is simplest way to handle JTable.
ID Verification using JSP
by Nouman Rashid
One of the most important parts of web development is to make sure that only authorized users get access to certain areas of the site. This tutorial takes a look at various steps involved in making JSP pages which validate a user ID and password from a MS Access database which contains the username and password.
Java Native Interface (JNI)
by Kanad Deshpande
Java Native Interface (JNI) is one of the intersting interface by java By using Java Native Interface (JNI) you can operate with other applications and libraries.
Understanding Hibernate ORM for Java/J2EE
by Saritha.S.V
Hibernate is the most popular and most complete open source object/relational mapping solution for Java environments.Hibernate's goal is to relieve the developer from 95 percent of common data persistence related programming tasks.
Login codes with JSP,JavaBean from mySQL database
by Prakash
my problem is can i have the code to login with the username and password using JSP and JavaBean/Servlets from mySQL database.When the user enters the username and password in the login page then it will go to the requested site.How to do it?
Java Speech Synthesizer
by David Barron
Small and simple. Type a sentence and press enter and your computer will speek to you.
simple Java Development Environment
by David Barron
Program in JAVA with ease, using this development environment, or adapt it to your own needs.
Turn EJB components into Web services
by Krunal J Patel
Web services have become the de facto standard for communication among applications. J2EE 1.4 allows stateless Enterprise JavaBeans (EJB) components to be exposed as Web services via a JAX-RPC (Java API for XML Remote Procedure Call) endpoint, allowing EJB applications to be exposed as Web services. This article presents a brief introduction to JAX-RPC, outlines the steps for exposing a stateless session bean as a Web service, and provides the best practices for exposing EJB components as Web services
CORBA Technology
by Krunal Patel
CORBA defines an architecture for distributed objects. The basic CORBA paradigm is that of a request for services of a distributed object. Everything else defined by the OMG is in terms of this basic paradigm.








Recent Forum Threads
•  Game:Colonization based with HTML5 Canvas and JavaScript
•  Pointwise.GridGen.v15.18
•  Global.Mapper.v15.2.3.b060614
•  Geometric_Glovius_Pro_v3.6.1
•  VERO.SurfCAM.v2014
•  Schlumberger.Petrel.V2013.2
•  Petrel.V2013.2
•  Altair.HyperWorks.v12
•  VoluMill.v6.1


Recent Articles
ASP GetTempName
Decode and Encode UTF-8
ASP GetFile
ASP FolderExists
ASP FileExists
ASP OpenTextFile
ASP FilesystemObject
ASP CreateFolder
ASP CreateTextFile
Javascript Get Selected Text


© Copyright codetoad.com 2001-2014