Monday, July 9, 2007

Hibernate tutorial

1. Introduction

Hibernate; the latest Open Source persistence technology at the heart of J2EE EJB 3.0 is available for download from Hibernet.org.TheHibernate core is 68,549 lines of Java code together with 27,948 lines of unit tests, all freely available under the LGPL, and has been in development for well over a year.

Hibernate, maps the Java classes to the database tables. It also provides the data query and retrieval facilities that significantly reduce the development time. Hibernate is not the best solutions for data centric applications that only uses the stored-procedures to implement the business logic in database. It is most useful with object-oriented domain modes and business logic in the Java-based middle-tier. Hibernate allows transparent persistence that enables the applications to switch any database. Hibernate can be used in Java Swing applications, Java Servlet-based applications, or J2EE applications using EJB session beans.

1.1 Features
  • Hibernate 3.0 provides three full-featured query facilities: Hibernate Query Language, the newly enhanced Hibernate Criteria Query API, and enhanced support for queries expressed in the native SQL dialect of the database.
  • Filters for working with temporal (historical), regional or permissioned data.
  • Enhanced Criteria query API: with full support for projection/aggregation and subselects.
  • Runtime performance monitoring: via JMX or local Java API, including a second-level cache browser.
  • Eclipse support, including a suite of Eclipse plug-ins for working with Hibernate 3.0, including mapping editor, interactive query prototyping, schema reverse engineering tool.
  • Hibernate is Free under LGPL: Hibernate can be used to develop/package and distribute the applications for free.
  • Hibernate is Scalable: Hibernate is very performant and due to its dual-layer architecture can be used in the clustered environments.
  • Less Development Time: Hibernate reduces the development timings as it supports inheritance, polymorphism, composition and the Java Collection framework.
  • Automatic Key Generation: Hibernate supports the automatic generation of primary key for your table
  • EJB3-style persistence operations: EJB3 defines the create() and merge() operations, which are slightly different to Hibernate's saveOrUpdate() and saveOrUpdateCopy() operations. Hibernate3 will support all four operations as methods of the Session interface.
  • Hibernate XML binding enables data to be represented as XML and POJOs interchangeably.
  • The EJB3 draft specification support for POJO persistence and annotations.

Hibernate Architecture


The above diagram shows that Hibernate is using the database and configuration data (properties and xml mapping) to provide persistence services (and persistent objects) to the application.

To use Hibernate, it is required to create Java classes that represents the table in the database and then map the instance variable in the class with the columns in the database. Then Hibernate can be used to perform operations on the database like select, insert, update and delete the records in the table. Hibernate automatically creates the query to perform these operations.

Hibernate architecture has three main components:

  • Connection Management: - Hibernate Connection management service provide efficient management of the database connections. Database connection is the most expensive part of interacting with the database as it requires a lot of resources of open and close the database connection.
  • Transaction Management: - Transaction management service provides the ability to the user to execute more than one database statements at a time.
  • Object relational Mapping: - Object relational mapping is technique of mapping the data representation from an object model to a relational data model. This part of the Hibernate is used to select, insert, update and delete the records form the underlying table. When we pass an object to a Session.save() method, Hibernate reads the state of the variables of that object and executes the necessary query.
  • Hibernate is very good tool as far as object relational mapping , but in terms of connection management and transaction management, it is lacking in performance and capabilities. So usually hibernate is being used with other connection management and transaction management tools. For example apache DBCP is used for connection pooling with the Hibernate.
  • Hibernate provides a lot of flexibility in use. It is called "Lite" architecture when we only use the object relational mapping component. While in "Full Cream" architecture all the three component Object Relational mapping, Connection Management and Transaction Management) are used.

    Hibernate Example

    This section demonstrates how to create a simple program to insert record in Oracle database. You can run this program from Eclipse or from command prompt as well.

    Configuring Hibernate:-

    In this application Hibernate provided the connection pooling and transaction management is used for simplicity. Hibernate uses the hibernate.cfg.xml to create the connection pool and setup required environment. Here is the code:

"-//Hibernate/Hibernate Configuration DTD//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

oracle.jdbc.driver.OracleDriver

jdbc:oracle:thin:@192.168.1.176:1521:CAM

wlnp

wlnp

10

true

org.hibernate.dialect.OracleDialect

update

In the above configuration file we specified to use the "CAM" which is running on “187.234.3.123” and the user of the database is “wlnp” with password “wlnp”. The dialect property is “org.hibernate.dialect.OracleDialect” which tells the Hibernate that we are using Oracle Database. Mapping resource specifies the table mapping to a POJO.

Hibernate, supports many database. With the use of the Hibernate (Object/Relational Mapping and Transparent Object Persistence for Java and SQL Databases), we can use the following databases dialect type property:

· DB2 - org.hibernate.dialect.DB2Dialect

· HypersonicSQL - org.hibernate.dialect.HSQLDialect

· Informix - org.hibernate.dialect.InformixDialect

· Ingres - org.hibernate.dialect.IngresDialect

· Interbase - org.hibernate.dialect.InterbaseDialect

· Pointbase - org.hibernate.dialect.PointbaseDialect

· PostgreSQL - org.hibernate.dialect.PostgreSQLDialect

· Mckoi SQL - org.hibernate.dialect.MckoiDialect

· Microsoft SQL Server - org.hibernate.dialect.SQLServerDialect

· MySQL - org.hibernate.dialect.MySQLDialect

· Oracle (any version) - org.hibernate.dialect.OracleDialect

· Oracle 9 - org.hibernate.dialect.Oracle9Dialect

· Progress - org.hibernate.dialect.ProgressDialect

· FrontBase - org.hibernate.dialect.FrontbaseDialect

· SAP DB - org.hibernate.dialect.SAPDBDialect

· Sybase - org.hibernate.dialect.SybaseDialect

· Sybase Anywhere - org.hibernate.dialect.SybaseAnywhereDialect

The property is the mapping for our contact table.

Hibernate JDBC Properties used :-

hibernate.connection.driver_class :-jdbc driver class

hibernate.connection.url :- jdbc URL

hibernate.connection.username :- database user

hibernate.connection.password :- database user password

hibernate.connection.pool_size :- maximum number of pooled connections

Hibernate.dialect :-The classname of a Hibernate Dialect

hibernate.show_sql :-Write all SQL statements to console (True/false).

hibernate.hbm2ddl.auto :- Automatically export schema DDL to the database when the SessionFactory is created. With create drop, the database schema will be dropped when the SessionFactory is closed explicitly. e.g. update | create | create-drop

Writing First Persistence Class: - Hibernate, uses the Plain Old Java Objects (POJOs) classes to map to the database table. We can configure the variables to map to the database column. Here is the code for Book. java:

/**

* Java Class to map to the database Book table

*/

package avakaya.book;

public class Book

{

private String bookId;

private String strBookName;

/**

* @return Returns the strBookName.

*/

public String getStrBookName()

{

return strBookName;

}

/**

* @param strBookName The strBookName to set.

*/

public void setStrBookName(String strBookName)

{

this.strBookName = strBookName;

}

/**

* Method getBookId

* Description :

* @return

*/

public String getBookId()

{

return bookId;

}

/**

* Method setBookId

* Description :

* @param string

*/

public void setBookId(String string)

{

bookId = string;

}

}

Mapping the Contact Object to the Database Contact table :- The file contact.hbm.xml is used to map Contact Object to the Contact table in the database. Here is the code for book.hbm.xml:

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

Setting Up Database :- Create a table Contact under the data base.

CREATE TABLE BOOK ( ID VARCHAR2(10 BYTE), NAME VARCHAR2(10 BYTE) ) LOGGING NOCACHE NOPARALLEL;

Developing Code to Test Hibernate example:-

package avakaya.book;

import org.hibernate.Session

import org.hibernate.SessionFactory;

import org.hibernate.Transaction;

import org.hibernate.cfg.Configuration;

/**

* Hibernate example to inset data into Book table

*/

public class BookAccess

{

public static void main(String[] args)

{

Session session = null;

try

{

// This step will read hibernate.cfg.xml and prepare hibernate for use

SessionFactory sessionFactory =

new Configuration().configure().buildSessionFactory();

session = sessionFactory.openSession();

Transaction tx = session.beginTransaction();

//Create new instance of Contact and set values in it by reading them from form object

System.out.println("Inserting Record");

Book book = new Book();

book.setBookId("12348");

book.setStrBookName("MyBook2");

session.save(book);

tx.commit();

System.out.println("Done");

}

catch (Exception e)

{

e.printStackTrace();

System.out.println(e.getMessage());

}

finally

{

if (session != null)

{

session.flush();

session.close();

}

}

}

}


Hibernate O/R mapping -A Look

Let us consider the following file to understand O/R Mapping




















Hibernate mapping documents are simple xml documents. Here are important elements of the mapping file:.

element
The first or root element of hibernate mapping document is element. Between the <hibernate-mapping> tag

· class element(s) are present.

· element
The element maps the class object with corresponding entity in the database. It also tells what table in the database has to access and what column in that table it should use. Within one element, several mappings are possible.

· element
The element in unique identifier to identify and object. In fact element map with the primary key of the table. In the example :

primary key maps to the ID field of the table CONTACT. The attributes of the id element are:

o name: The property name used by the persistent class.

o column: The column used to store the primary key value.

o type: The Java data type used.

o unsaved-value: This is the value used to determine if a class has been made persistent. If the value of the id attribute is null, then it means that this object has not been persisted.

· element
The method is used to generate the primary key for the new record. Here are some of the commonly used generators:

* Increment - This is used to generate primary keys of type long, short or int that are unique only. It should not be used in the clustered deployment environment.

* Sequence - Hibernate can also use the sequences to generate the primary key. It can be used with DB2, PostgreSQL, Oracle, SAP DB databases.

* Assigned - Assigned method is used when application code generates the primary key.

· element
The property elements define standard Java attributes and their mapping into database schema. The property element supports the column child
element to specify additional properties, such as the index name on a column or a specific column type.

1.1. Understanding Hibernate element

In this section we will look into the element and its options.Hibernate generator element generates the primary key for new record. There are many options provided by the generator method to be used in different situations.

The element

This is the optional element under element. The element is used to specify the class name to be used to generate the primary key for new record while saving a new record. The element is used to pass the parameter (s) to the class. Here is the example of generator element from our first application In this case element do not generate the primary key and it is required to set the primary key value before calling save() method.

Here is the lists of some commonly used generators in hibernate:

Generator

Description

increment

It generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. It should not the used in the clustered environment.

identity

It supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.

sequence

The sequence generator uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int

hilo

The hilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database. Do not use this generator with connections enlisted with JTA or with a user-supplied connection.

seqhilo

The seqhilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a named database sequence.

uuid

The uuid generator uses a 128-bit UUID algorithm to generate identifiers of type string, unique within a network (the IP address is used). The UUID is encoded as a string of hexadecimal digits of length 32.

guid

It uses a database-generated GUID string on MS SQL Server and MySQL.

native

It picks identity, sequence or hilo depending upon the capabilities of the underlying database.

assigned

lets the application to assign an identifier to the object before save() is called. This is the default strategy if no element is specified.

select

retrieves a primary key assigned by a database trigger by selecting the row by some unique key and retrieving the primary key value.

foreign

uses the identifier of another associated object. Usually used in conjunction with a primary key association.

1.1. Using Hibernate to generate id incrementally

As we have seen in the last section that the increment class generates identifiers of type long, short or int that is unique only when no other process is inserting data into the same table. In this lesson I will show you how to write running program to demonstrate it. You should not use this method to generate the primary key in case of clustured environment.

In this section we will create/alter table in database, add mappings in the book.hbm.xml file, develop/modify the POJO class (Book.java), and write the program to test it out.

Create Table in the database:
User the following sql statement to create a new table in the database

CREATE TABLE BOOK ( ID INTEGER DEFAULT 0, BOOKNAME VARCHAR2(50 BYTE) DEFAULT NULL ) LOGGING NOCACHE NOPARALLEL;

Developing POJO Class (Book.java)
Book.java is our POJO class which is to be persisted to the database table "book”

/**

* Java Class to map to the database Book table

*/

package avakaya.book;

/**

* Class Book

* Description : POJO

* @version $Revision: 1.0 $

*/

public class Book {

private int lngBookId;

private String strBookName;

/**

* @return Returns the lngBookId.

*/

public int getLngBookId() {

return lngBookId;

}

/**

* @param lngBookId The lngBookId to set.

*/

public void setLngBookId(int lngBookId) {

this.lngBookId = lngBookId;

}

/**

* @return Returns the strBookName.

*/

public String getStrBookName() {

return strBookName;

}

/**

* @param strBookName The strBookName to set.

*/

public void setStrBookName(String strBookName) {

this.strBookName = strBookName;

}

}

Adding Mapping entries to existing.hbm.xml / book.hbm.xml
Add the following mapping code into the contact.hbm.xml file

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

Note:- We have used !!!

Adding > to hibernate.cfg.xml

"-//Hibernate/Hibernate Configuration DTD//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

oracle.jdbc.driver.OracleDriver

jdbc:oracle:thin:@192.168.1.176:1521:CAM

wlnp

wlnp

10

true

org.hibernate.dialect.OracleDialect

update

Write the client program and test it out
Here is the code of our client program to test the application

/****************************************************************************

* @(#) IdIncrementExample.java Feb 22, 2006

****************************************************************************/

package avakaya.book;

//Hibernate Imports

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

/**

* Class

* Description :

* @version $Revision: 1.0 $

* @author Avakaya R

*

*/

public class IdIncrementExample

{

public static void main(String[] args)

{

Session session = null;

try

{

// This step will read hibernate.cfg.xml and prepare hibernate for use

SessionFactory sessionFactory =

new Configuration().configure().buildSessionFactory();

session = sessionFactory.openSession();

org.hibernate.Transaction tx = session.beginTransaction();

//Create new instance of Contact and set values in it by reading them from form object

System.out.println("Inserting Book object into database..");

Book book = new Book();

book.setStrBookName("Hibernate Tutorial2");

session.save(book);

System.out.println("Book object persisted to the database.");

tx.commit();

session.flush();

session.close();

}

catch (Exception e)

{

System.out.println(e.getMessage());

}

finally

{

}

}

}

Hibernate Querey Language

Hibernate Query Language or HQL for short is extremely powerful query language. HQL is much like SQL and are case-insensitive, except for the names of the Java Classes and properties. Hibernate Query Language is used to execute queries against database. Hibernate automatically generates the sql query and execute it against underlying database if HQL is used in the application. HQL is based on the relational object models and makes the SQL object oriented. Hibernate Query Language uses Classes and properties instead of tables and columns. Hibernate Query Language is extremely powerful and it supports Polymorphism, Associations, Much less verbose than SQL.

There are other options that can be used while using Hibernate. These are Query By Criteria (QBC) and Query BY Example (QBE) using Criteria API and the Native SQL queries. In this section we will understand HQL in detail.

Why to use HQL?

  • Full support for relational operations: HQL allows representing SQL queries in the form of objects. Hibernate Query Language uses Classes and properties instead of tables and columns.
  • Return result as Object: The HQL queries return the query result(s) in the form of object(s), which is easy to use. This elemenates the need of creating the object and populate the data from result set.
  • Polymorphic Queries: HQL fully supports polymorphic queries. Polymorphic queries results the query results along with all the child objects if any.
  • Easy to Learn: Hibernate Queries are easy to learn and it can be easily implemented in the applications.
  • Support for Advance features: HQL contains many advance features such as pagination, fetch join with dynamic profiling, Inner/outer/full joins, Cartesian products. It also supports Projection, Aggregation (max, avg) and grouping, Ordering, Sub queries and SQL function calls.
  • Database independent: Queries written in HQL are database independent (If database supports the underlying feature).

Understanding HQL Syntax
Any Hibernate Query Language may consist of following elements:

  • Clauses
  • Aggregate functions
  • Subqueries

Clauses in the HQL are:

  • from
  • select
  • where
  • order by
  • group by

Aggregate functions are:

  • avg(...), sum(...), min(...), max(...)
  • count(*)
  • count(...), count(distinct ...), count(all...)

Subqueries
Subqueries are nothing but it’s a query within another query. Hibernate supports Subqueries if the underlying database supports it.

1.1. Preparing table for HQL Examples

Create an insurance table

CREATE TABLE Insurance (

ID INTEGER default 0,

insurance_name varchar(50) default NULL,

invested_amount INTEGER default NULL,

investement_date DATE default NULL,

PRIMARY KEY (ID)

)

Insert rows :-

insert into insurance values (1, 'Car Insurance', 1000,to_date('2003/05/03 21:02:44', 'yyyy/mm/dd hh24:mi:ss'));

insert into insurance values (2,'Life Insurance',100,to_date('2005-10-01 00:00:00', 'yyyy/mm/dd hh24:mi:ss'));

insert into insurance values (3,'Life Insurance',500,to_date('2005-10-15 00:00:00', 'yyyy/mm/dd hh24:mi:ss'));

insert into insurance values (4,'Car Insurance',2500,to_date('2005-01-01 00:00:00', 'yyyy/mm/dd hh24:mi:ss'));

insert into insurance values (5,'Dental Insurance',500,to_date('2004-01-01 00:00:00', 'yyyy/mm/dd hh24:mi:ss'));

insert into insurance values (6,'Life Insurance',900,to_date('2003-01-01 00:00:00', 'yyyy/mm/dd hh24:mi:ss'));

insert into insurance values (7,'Travel Insurance',2000,to_date('2005-02-02 00:00:00', 'yyyy/mm/dd hh24:mi:ss'));

insert into insurance values (8,'Travel Insurance',600,to_date('2005-03-03 00:00:00', 'yyyy/mm/dd hh24:mi:ss'));

insert into insurance values (9,'Medical Insurance',700,to_date('2005-04-04 00:00:00', 'yyyy/mm/dd hh24:mi:ss'));

insert into insurance values (10,'Medical Insurance',900,to_date('2005-03-03 00:00:00', 'yyyy/mm/dd hh24:mi:ss'));

insert into insurance values (11,'Home Insurance',800,to_date('2005-02-02 00:00:00', 'yyyy/mm/dd hh24:mi:ss'));

insert into insurance values (12,'Home Insurance',750,to_date('2004-09-09 00:00:00', 'yyyy/mm/dd hh24:mi:ss'));

insert into insurance values (13,'Motorcycle Insurance',900,to_date('2004-06-06 00:00:00', 'yyyy/mm/dd hh24:mi:ss'));

insert into insurance values (14,'Motorcycle Insurance',780,to_date('2005-03-03 00:00:00', 'yyyy/mm/dd hh24:mi:ss'));

Above Sql query will create insurance table and add the following data:


2 comments:

Anonymous said...

Hi!

Also some basics at:

http://www.hibernatetutorial.com

regards
Tom

Anonymous said...

What a great web log. I spend hours on the net reading blogs, about tons of various subjects. I have to first of all give praise to whoever created your theme and second of all to you for writing what i can only describe as an fabulous article. I honestly believe there is a skill to writing articles that only very few posses and honestly you got it. The combining of demonstrative and upper-class content is by all odds super rare with the astronomic amount of blogs on the cyberspace.