Hibernate Concepts
Hibernate Concepts
25/05/2010
Abhishek Jain
[email protected]
Introduction to Hibernate:-
Hibernate is java based middleware designed to complete the Object-Relational(O/R) mapping
model. It maps an object-oriented domain model to a traditional relational database. Primary
feature of hibernate is mapping from Java classes to database tables (and from Java data types
to SQL data types). Hibernate also provides data query and retrieval facilities. Hibernate
generates the SQL calls and relieves the developer from manual result set handling and object
conversion, keeping the application portable to all supported SQL databases, with database
portability delivered at very little performance overhead. Hibernate can be used in both
standalone java applications and Java EE applications.
Why Hibernate:
1. Hibernate is a open source framework.
2. Hibernate provides supports for collections and object relations.
3. Hibernate was introduced to address the issues of Entity Beans, like extremely slow and
complexity.
4. It uses XML based configuration files for mapping.
5. Hibernate APIs are very simple to learn and use.
6. It provided 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.
Hibernate Configuration:
1. Configure the mapping files for you application.
2. Specify connection properties.
3. Configure connection pooling.
4. Configure hibernate logging.
5. Specify dialects.
6. Configure transactions.
7. Specify caching strategy
Hibernate uses the hibernate.cfg.xml to create the connection pool and setup required
environment.
Note:- hibernate-3.jar is the one you will require while using this framework.
Sample Hibernate configuration file:
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/hibernatesample</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mapping files -->
<mapping resource="sample.hbm.xml"/>
</session-factory>
</hibernate-configuration>
In the above configuration file I specified to use the "hibernatesample" 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, 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 <mapping resource="sample.hbm.xml"/> property is the mapping for our sample table.
Sample.java
package com.app;
}
}
Mapping of Sample class to the Database Sample Table:
The file sample.hbm.xml will be used to map the Sample class to Database sample table.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.app.Sample" table="SAMPLE">
<id name="id" type="long" column="ID" >
<generator class="assigned"/>
</id>
<property name="name">
<column name="NAME" />
</property>
</class>
</hibernate-mapping>
Hibernate mapping documents are simple xml documents. Here are important elements of the
mapping file:.
1. <hibernate-mapping> element
The first or root element of hibernate mapping document is <hibernate-mapping>
element. Between the <hibernate-mapping> tag class element(s) are present.
2. <class> element
The <Class> 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 <hibernate-mapping> element, several <class> mappings are
possible.
3. <id> element
The <id> element in unique identifier to identify and object. In fact <id> element map
with the primary key of the table. In our code :
<id name="id" type="long" column="ID" >
primary key maps to the ID field of the table SAMPLE. The attributes of the id element are:
4. <generator> element
The <generator> method is used to generate the primary key for the new record. Here is
some of the commonly used generators :
A. 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.
B. Sequence - Hibernate can also use the sequences to generate the primary key. It
can be used with DB2, PostgreSQL, Oracle, SAP DB databases.
C. Assigned - Assigned method is used when application code generates the primary
key.
5. <property> 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.
As in the configuration file (hibernate.cfg.xml), I have already specified that for this sample
application I have used MySQL hibernatesample database running on localhost.
Now to test the code which I have written we need to write one more Java Class. Below is the
code.
package com.app;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* @author Abhishek Jain
*
* Hibernate example to inset data into Sample table
*/
public class Example {
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 Sample and set values in it by reading them from form object
System.out.println("Record insertion starts from here");
Sample sampApp = new Sample();
sampApp.setId(3);
sampApp.setName("Abhishek");
session.save(sampApp);
System.out.println("Done");
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
session.flush();
session.close();
}
}
In the above mention code Hibernate Session is the main runtime interface between a Java
application and Hibernate. We will always require to get the Hibernate Session.SessionFactory
which will allow 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 sample
information(name and Id) to the database. Below is the definition of SessionFactory and
Session object from Hibernate Docs.
SessionFactory (org.hibernate.SessionFactory):- A threadsafe, immutable cache of compiled
mappings for a single database. A factory for Session and a client of ConnectionProvider,
SessionFactory can hold an optional (second-level) cache of data that is reusable between
transactions at a process, or cluster, level.
Conclusion:-
This document is just for introduction to what Hibernate can do. Hibernate delivers a high-
performance, open source persistence framework comparable to many of its open source and
commercial counterparts. Developers utilizing Hibernate can greatly reduce the amount of time
and effort needed to code, test, and deploy applications.