Hibernate 3.0

What is Hibernate?
Hibernate 3.0, the latest Open Source persistence technology
at the heart of J2EE EJB 3.0 is available for download from Hibernet.org.The Hibernate 3.0 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 reduces 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.

Features of Hibernate

* 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.

* JDK 1.5 Enhancements: The new JDK has been released as a preview earlier this year and we expect a slow migration to the new 1.5 platform throughout 2004. While Hibernate3 still runs perfectly with JDK 1.2, Hibernate3 will make use of some new JDK features. JSR 175 annotations, for example, are a perfect fit for Hibernate metadata and we will embrace them aggressively. We will also support Java generics, which basically boils down to allowing type safe collections.


* Hibernate XML binding enables data to be represented as XML and POJOs interchangeably.

Detailed features are available at http://www.hibernate.org/About/RoadMap.

In this lesson you will learn the architecture of Hibernate. The following diagram describes the high level
architecture of hibernate:

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 provide 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 is concern, 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 uses the object relational mapping component. While in "Full Cream" architecture all the three component Object Relational mapping, Connection Management and Transaction Management) are used.

Writing First Hibernate Code

In this section I will show you how to create a simple program to insert record in MySQL database. You can run this program from Eclipse or from command prompt as well. I am assuming that you are familiar with MySQL and Eclipse environment.

Configuring Hibernate
In this application
Hibernate provided 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">





com.mysql.jdbc.Driver



jdbc:mysql://localhost/hibernatetutorial

root

10
true
org.hibernate.dialect.MySQLDialect
update





In the above configuration file we specified to use the "hibernatetutorial" which is running on localhost and the user of the database is root with no password. The dialect property is org.hibernate.dialect.MySQLDialect which tells the Hibernate that we are using MySQL Database. 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.

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 Contact.java:
package roseindia.tutorial.hibernate;

/**
* @author Deepak Kumar
*
* Java Class to map to the datbase Contact Table
*/
public class Contact {
private String firstName;
private String lastName;
private String email;
private long id;

/**
* @return Email
*/
public String getEmail() {
return email;
}

/**
* @return First Name
*/
public String getFirstName() {
return firstName;
}

/**
* @return Last name
*/
public String getLastName() {
return lastName;
}

/**
* @param string Sets the Email
*/
public void setEmail(String string) {
email = string;
}

/**
* @param string Sets the First Name
*/
public void setFirstName(String string) {
firstName = string;
}

/**
* @param string sets the Last Name
*/
public void setLastName(String string) {
lastName = string;
}

/**
* @return ID Returns ID
*/
public long getId() {
return id;
}

/**
* @param l Sets the ID
*/
public void setId(long l) {
id = l;
}

}

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 contact.hbm.xml:

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">



















Setting Up MySQL Database
In the configuration file(hibernate.cfg.xml) we have specified to use hibernatetutorial database running on localhost. So, create the databse ("hibernatetutorial") on the MySQL server running on localhost.

Developing Code to Test Hibernate example
Now we are ready to write a program to insert the data into database. We should first understand about the Hibernate's Session. Hibernate Session is the main runtime interface
between a Java application and Hibernate. First we are required to get the Hibernate Session.SessionFactory allows application to create the Hibernate Sesssion by reading the configuration from hibernate.cfg.xml file. Then the save method on session object is used to save the contact information to the database:

session.save(contact)

Here is the code of FirstExample.java


package roseindia.tutorial.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


/**
* @author Deepak Kumar
*
* http://www.roseindia.net
* Hibernate example to inset data into Contact table
*/
public class FirstExample {
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();
//Create new instance of Contact and set

values in it by reading them from form object
System.out.println("Inserting Record");
Contact contact = new Contact();
contact.setId(3);
contact.setFirstName("Deepak");
contact.setLastName("Kumar");
contact.setEmail("deepak_38@yahoo.com");
session.save(contact);
System.out.println("Done");
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
// Actual contact insertion will happen at this step
session.flush();
session.close();

}

}

http://www.roseindia.net/struts/hibernate-spring/index.shtml
}