Hibernate
Hibernate
Hibernate
Hibernate maps Java classes to database tables and from Java data types to SQL
data types and relieves the developer from 95% of common data persistence
related programming tasks.
Hibernate sits between traditional Java objects and database server to handle all the
works in persisting those objects based on the appropriate O/R mechanisms and
patterns.
Hibernate Advantages
Hibernate takes care of mapping Java classes to database tables using XML
files and without writing any line of code.
Provides simple APIs for storing and retrieving Java objects directly to and
from the database.
If there is change in the database or in any table, then you need to change
the XML file properties only.
Abstracts away the unfamiliar SQL types and provides a way to work around
familiar Java Objects.
Supported Databases
Hibernate supports almost all the major RDBMS. Following is a list of few of the
database engines supported by Hibernate −
DB2/NT
MySQL
PostgreSQL
FrontBase
Oracle
Supported Technologies
Hibernate supports a variety of other technologies, including −
XDoclet Spring
J2EE
Eclipse plug-ins
Maven
Hibernate Framework
Hibernate is a Java framework that simplifies the development of Java application to interact with
the database. It is an open source, lightweight, ORM (Object Relational Mapping) tool. Hibernate
implements the specifications of JPA (Java Persistence API) for data persistence.
ORM Tool
An ORM tool simplifies the data creation, data manipulation and data access. It is a programming
technique that maps the object to the data stored in the database.
The ORM tool internally uses the JDBC API to interact with the database.
What is JPA?
Java Persistence API (JPA) is a Java specification that provides certain functionality and standard
to ORM tools. The javax.persistence package contains the JPA classes and interfaces.
Hibernate framework is open source under the LGPL license and lightweight.
2) Fast Performance
The performance of hibernate framework is fast because cache is internally used in hibernate
framework. There are two types of cache in hibernate framework first level cache and second level
cache. First level cache is enabled by default.
HQL (Hibernate Query Language) is the object-oriented version of SQL. It generates the database
independent queries. So you don't need to write database specific queries. Before Hibernate, if
database is changed for the project, we need to change the SQL query as well that leads to the
maintenance problem.
Hibernate framework provides the facility to create the tables of the database automatically. So
there is no need to create tables in the database manually.
Hibernate supports Query cache and provide statistics about query and database status.
Hibernate Architecture
1. Hibernate Architecture
2. Elements of Hibernate Architecture
1. SessionFactory
2. Session
3. Transaction
4. ConnectionProvider
5. TransactionFactory
The Hibernate architecture includes many objects such as persistent object, session factory,
transaction factory, connection factory, session, transaction etc.
This is the high level architecture of Hibernate with mapping file and configuration file.
Hibernate framework uses many objects such as session factory, session, transaction etc.
alongwith existing Java API such as JDBC (Java Database Connectivity), JTA (Java Transaction API)
and JNDI (Java Naming Directory Interface).
SessionFactory
The SessionFactory is a factory of session and client of ConnectionProvider. It holds second level
cache (optional) of data. The org.hibernate.SessionFactory interface provides factory method to
get the object of Session.
Session
The session object provides an interface between the application and data stored in the database.
It is a short-lived object and wraps the JDBC connection. It is factory of Transaction, Query and
Criteria. It holds a first-level cache (mandatory) of data. The org.hibernate.Session interface
provides methods to insert, update and delete the object. It also provides factory methods for
Transaction, Query and Criteria.
Transaction
The transaction object specifies the atomic unit of work. It is optional. The
org.hibernate.Transaction interface provides methods for transaction management.
ConnectionProvider
TransactionFactory
What is ORM?
ORM stands for Object-Relational Mapping (ORM) is a programming technique for
converting data between relational databases and object oriented programming
languages such as Java, C#, etc.
Sr.No. Advantages
Sr.No. Solutions
2 A language or API to specify queries that refer to classes and properties of classes.
Castor
TopLink
Spring DAO
Hibernate
Hibernate Environment
Downloading Hibernate
It is assumed that you already have the latest version of Java installed on your
system. Following are the simple steps to download and install Hibernate on your
system −
Installing Hibernate
Once you downloaded and unzipped the latest version of the Hibernate Installation
file, you need to perform following two simple steps. Make sure you are setting your
CLASSPATH variable properly otherwise you will face problem while compiling your
application.
Now, copy all the library files from /lib into your CLASSPATH, and change
your classpath variable to include all the JARs −
Finally, copy hibernate3.jar file into your CLASSPATH. This file lies in the
root directory of the installation and is the primary JAR that Hibernate needs
to do its work.
Hibernate Prerequisites
Following is the list of the packages/libraries required by Hibernate and you should
install them before starting with Hibernate. To install these packages, you will have
to copy library files from /lib into your CLASSPATH, and change your CLASSPATH
variable accordingly.
Sr.No. Packages/Libraries
1 dom4j
2 Xalan
XSLT Processor https://xml.apache.org/xalan-j/
3 Xerces
4 cglib
5 log4j
6 Commons
7 SLF4J
Hibernate - Configuration
Hibernate Properties
Following is the list of important properties, you will be required to configure for a
databases in a standalone situation −
Sr.No. Properties & Description
1 hibernate.dialect
This property makes Hibernate generate the appropriate SQL for the chosen
database.
2 hibernate.connection.driver_class
3 hibernate.connection.url
4 hibernate.connection.username
5 hibernate.connection.password
6 hibernate.connection.pool_size
7 hibernate.connection.autocommit
If you are using a database along with an application server and JNDI, then you
would have to configure the following properties −
1 hibernate.connection.datasource
The JNDI name defined in the application server context, which you are using
for the application.
2 hibernate.jndi.class
3 hibernate.jndi.<JNDIpropertyname>
5 hibernate.connection.username
6 hibernate.connection.password
The XML configuration file must conform to the Hibernate 3 Configuration DTD,
which is available at http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd.
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
org.hibernate.dialect.MySQLDialect
</property>
com.mysql.jdbc.Driver
</property>
jdbc:mysql://localhost/test
</property>
root
</property>
root123
</property>
</session-factory></hibernate-configuration>
The above configuration file includes <mapping> tags, which are related to
hibernatemapping file and we will see in next chapter what exactly a hibernate
mapping file is and how and why do we use it?
1 DB2
org.hibernate.dialect.DB2Dialect
2 HSQLDB
org.hibernate.dialect.HSQLDialect
3 HypersonicSQL
org.hibernate.dialect.HSQLDialect
4 Informix
org.hibernate.dialect.InformixDialect
5 Ingres
org.hibernate.dialect.IngresDialect
6 Interbase
org.hibernate.dialect.InterbaseDialect
org.hibernate.dialect.SQLServerDialect
org.hibernate.dialect.SQLServer2005Dialect
org.hibernate.dialect.SQLServer2008Dialect
10 MySQL
org.hibernate.dialect.MySQLDialect
org.hibernate.dialect.OracleDialect
12 Oracle 11g
org.hibernate.dialect.Oracle10gDialect
13 Oracle 10g
org.hibernate.dialect.Oracle10gDialect
14 Oracle 9i
org.hibernate.dialect.Oracle9iDialect
15 PostgreSQL
org.hibernate.dialect.PostgreSQLDialect
16 Progress
org.hibernate.dialect.ProgressDialect
17 SAP DB
org.hibernate.dialect.SAPDBDialect
18 Sybase
org.hibernate.dialect.SybaseDialect
19 Sybase Anywhere
org.hibernate.dialect.SybaseAnywhereDialect
Hibernate - Sessions
A Session is used to get a physical connection with a database. The Session object
is lightweight and designed to be instantiated each time an interaction is needed
with the database. Persistent objects are saved and retrieved through a Session
object.
The session objects should not be kept open for a long time because they are not
usually thread safe and they should be created and destroyed them as needed. The
main function of the Session is to offer, create, read, and delete operations for
instances of mapped entity classes.
Instances may exist in one of the following three states at a given point in time −
try {
tx = session.beginTransaction();
// do some work
...
tx.commit();}
catch (Exception e) {
if (tx!=null) tx.rollback();
e.printStackTrace(); } finally {
session.close();}
If the Session throws an exception, the transaction must be rolled back and the
session must be discarded.
1 Transaction beginTransaction()
2 void cancelQuery()
3 void clear()
End the session by releasing the JDBC connection and cleaning up.
Create a new Criteria instance, for the given entity class, or a superclass of an
entity class.
Return the identifier value of the given entity as associated with this session.
Create a new instance of Query for the given collection and filter string.
Create a new instance of Query for the given HQL query string.
Create a new instance of SQLQuery for the given SQL query string.
Return the persistent instance of the given named entity with the given
identifier, or null if there is no such persistent instance.
14 SessionFactory getSessionFactory()
16 Transaction getTransaction()
17 boolean isConnected()
18 boolean isDirty()
Does this session contain any changes which must be synchronized with the
database?
19 boolean isOpen()
Update the persistent instance with the identifier of the given detached
instance.
Update the persistent instance with the identifier of the given detached
instance.
The entire concept of Hibernate is to take the values from Java class attributes and
persist them to a database table. A mapping document helps Hibernate in
determining how to pull the values from the classes and map them with table and
associated fields.
Java classes whose objects or instances will be stored in database tables are called
persistent classes in Hibernate. Hibernate works best if these classes follow some
simple rules, also known as the Plain Old Java Object (POJO) programming
model.
There are following main rules of persistent classes, however, none of these rules
are hard requirements −
All attributes that will be persisted should be declared private and have
getXXX and setXXX methods defined in the JavaBean style.
All classes that do not extend or implement some specialized classes and
interfaces required by the EJB framework.
The POJO name is used to emphasize that a given object is an ordinary Java Object,
not a special object, and in particular not an Enterprise JavaBean.
Simple POJO Example
Based on the few rules mentioned above, we can define a POJO class as follows −
public Employee() {}
this.firstName = fname;
this.lastName = lname;
this.salary = salary;
return id;
this.id = id;
return firstName;
this.firstName = first_name;
}
public String getLastName() {
return lastName;
this.lastName = last_name;
return salary;
this.salary = salary;
}}
Though many Hibernate users choose to write the XML by hand, but a number of
tools exist to generate the mapping document. These include XDoclet, Middlegen
and AndroMDA for the advanced Hibernate users.
Let us consider our previously defined POJO class whose objects will persist in the
table defined in next section.
public Employee() {}
this.firstName = fname;
this.lastName = lname;
this.salary = salary;
return id;
this.id = id;
return firstName;
this.firstName = first_name;
return lastName;
}
this.lastName = last_name;
return salary;
this.salary = salary;
}}
There would be one table corresponding to each object you are willing to provide
persistence. Consider above objects need to be stored and retrieved into the
following RDBMS table −
Based on the two above entities, we can define following mapping file, which
instructs Hibernate how to map the defined class or classes to the database tables.
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
</meta>
<generator class="native"/>
</id>
</class></hibernate-mapping>
You should save the mapping document in a file with the format
<classname>.hbm.xml. We saved our mapping document in the file
Employee.hbm.xml.
Let us see understand a little detail about the mapping elements used in the
mapping file −
The <class> elements are used to define specific mappings from a Java
classes to the database tables. The Java class name is specified using the
name attribute of the class element and the database tablename is
specified using the table attribute.
The <meta> element is optional element and can be used to create the
class description.
The <id> element maps the unique ID attribute in class to the primary key
of the database table. The name attribute of the id element refers to the
property in the class and the column attribute refers to the column in the
database table. The type attribute holds the hibernate mapping type, this
mapping types will convert from Java to SQL data type.
There are other attributes and elements available, which will be used in a mapping
document and I would try to cover as many as possible while discussing other
Hibernate related topics.
When you prepare a Hibernate mapping document, you find that you map the Java
data types into RDBMS data types. The types declared and used in the mapping
files are not Java data types; they are not SQL database types either. These types
are called Hibernate mapping types, which can translate from Java to SQL data
types and vice versa.
This chapter lists down all the basic, date and time, large object, and various other
builtin mapping types.
Primitive Types
Mapping type Java type ANSI SQL Type
JDK-related Types
Mapping type Java type ANSI SQL Type
So far, we have seen very basic O/R mapping using hibernate, but there are three
most important mapping topics, which we have to learn in detail.
These are −
Mapping of collections,
Component Mappings.
Collections Mappings
If an entity or class has collection of values for a particular variable, then we can
map those values using any one of the collection interfaces available in java.
Hibernate can persist instances of java.util.Map, java.util.Set,
java.util.SortedMap, java.util.SortedSet, java.util.List, and any array of
persistent entities or values.
Sr.No. Collection type & Mapping Description
1 java.util.Set
This is mapped with a <set> element and initialized with java.util.HashSet
2 java.util.SortedSet
This is mapped with a <set> element and initialized with java.util.TreeSet.
The sort attribute can be set to either a comparator or natural ordering.
3 java.util.List
This is mapped with a <list> element and initialized with java.util.ArrayList
4 java.util.Collection
This is mapped with a <bag> or <ibag> element and initialized with
java.util.ArrayList
5 java.util.Map
This is mapped with a <map> element and initialized with java.util.HashMap
6 java.util.SortedMap
This is mapped with a <map> element and initialized with java.util.TreeMap.
The sort attribute can be set to either a comparator or natural ordering.
Arrays are supported by Hibernate with <primitive-array> for Java primitive value
types and <array> for everything else. However, they are rarely used, so I am not
going to discuss them in this tutorial.
If you want to map a user defined collection interfaces, which is not directly
supported by Hibernate, you need to tell Hibernate about the semantics of your
custom collections, which is not very easy and not recommend to be used.
Association Mappings
The mapping of associations between entity classes and the relationships between
tables is the soul of ORM. Following are the four ways in which the cardinality of the
relationship between the objects can be expressed. An association mapping can be
unidirectional as well as bidirectional.
1 Many-to-One
Mapping many-to-one relationship using Hibernate
2 One-to-One
Mapping one-to-one relationship using Hibernate
3 One-to-Many
Mapping one-to-many relationship using Hibernate
4 Many-to-Many
Mapping many-to-many relationship using Hibernate
Component Mappings
It is very much possible that an Entity class can have a reference to another class as
a member variable. If the referred class does not have its own life cycle and
completely depends on the life cycle of the owning entity class, then the referred
class hence therefore is called as the Component class.
1 Component Mappings
Mapping for a class having a reference to another class as a member variable.
Hibernate - Annotations
So far you have seen how Hibernate uses XML mapping file for the transformation
of data from POJO to database tables and vice versa. Hibernate annotations are the
newest way to define mappings without the use of XML file. You can use
annotations in addition to or as a replacement of XML mapping metadata.
Hibernate Annotations is the powerful way to provide the metadata for the Object
and Relational Table mapping. All the metadata is clubbed into the POJO java file
along with the code, this helps the user to understand the table structure and POJO
simultaneously during the development.
If you going to make your application portable to other EJB 3 compliant ORM
applications, you must use annotations to represent the mapping information, but
still if you want greater flexibility, then you should go with XML-based mappings.
Second, you will need to install the Hibernate 3.x annotations distribution package,
available from the sourceforge: (Download Hibernate Annotation) and copy
hibernate-annotations.jar, lib/hibernate-comons-annotations.jar and
lib/ejb3-persistence.jar from the Hibernate Annotations distribution to your
CLASSPATH.
Consider we are going to use the following EMPLOYEE table to store our objects −
Following is the mapping of Employee class with annotations to map objects with
the defined EMPLOYEE table −
import javax.persistence.*;
@Id @GeneratedValue
@Column(name = "id")
@Column(name = "first_name")
@Column(name = "last_name")
public Employee() {}
return id;
this.id = id;
return firstName;
this.firstName = first_name;
return lastName;
this.lastName = last_name;
}
public int getSalary() {
return salary;
this.salary = salary;
}}
Hibernate detects that the @Id annotation is on a field and assumes that it should
access properties of an object directly through fields at runtime. If you placed the
@Id annotation on the getId() method, you would enable access to properties
through getter and setter methods by default. Hence, all other annotations are also
placed on either fields or getter methods, following the selected strategy.
Following section will explain the annotations used in the above class.
@Entity Annotation
The EJB 3 standard annotations are contained in the javax.persistencepackage,
so we import this package as the first step. Second, we used the @Entity
annotation to the Employee class, which marks this class as an entity bean, so it
must have a no-argument constructor that is visible with at least protected scope.
@Table Annotation
The @Table annotation allows you to specify the details of the table that will be
used to persist the entity in the database.
The @Table annotation provides four attributes, allowing you to override the name
of the table, its catalogue, and its schema, and enforce unique constraints on
columns in the table. For now, we are using just table name, which is EMPLOYEE.
By default, the @Id annotation will automatically determine the most appropriate
primary key generation strategy to be used but you can override this by applying
the @GeneratedValue annotation, which takes two parameters strategy and
generator that I'm not going to discuss here, so let us use only the default key
generation strategy. Letting Hibernate determine which generator type to use makes
your code portable between different databases.
@Column Annotation
The @Column annotation is used to specify the details of the column to which a
field or property will be mapped. You can use column annotation with the following
most commonly used attributes −
length attribute permits the size of the column used to map a value
particularly for a String value.
nullable attribute permits the column to be marked NOT NULL when the
schema is generated.
configure().
addAnnotatedClass(Employee.class).
buildSessionFactory();
ME.listEmployees();
ME.updateEmployee(empID1, 5000);
ME.deleteEmployee(empID2);
ME.listEmployees();
}
Transaction tx = null;
try {
tx = session.beginTransaction();
employee.setFirstName(fname);
employee.setLastName(lname);
employee.setSalary(salary);
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
return employeeID;
Transaction tx = null;
try {
tx = session.beginTransaction();
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
Transaction tx = null;
try {
tx = session.beginTransaction();
employee.setSalary( salary );
session.update(employee);
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.delete(employee);
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}}
Database Configuration
Now let us create hibernate.cfg.xml configuration file to define database related
parameters.
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
org.hibernate.dialect.MySQLDialect
</property>
com.mysql.jdbc.Driver
</property>
jdbc:mysql://localhost/test
</property>
root
</property>
cohondob
</property>
</session-factory></hibernate-configuration>
You would get the following result, and records would be created in EMPLOYEE
table.
Although you can use SQL statements directly with Hibernate using Native SQL, but
I would recommend to use HQL whenever possible to avoid database portability
hassles, and to take advantage of Hibernate's SQL generation and caching
strategies.
Keywords like SELECT, FROM, and WHERE, etc., are not case sensitive, but
properties like table and column names are case sensitive in HQL.
FROM Clause
You will use FROM clause if you want to load a complete persistent objects into
memory. Following is the simple syntax of using FROM clause −
If you need to fully qualify a class name in HQL, just specify the package and class
name as follows −
AS Clause
The AS clause can be used to assign aliases to the classes in your HQL queries,
especially when you have the long queries. For instance, our previous simple
example would be the following −
The AS keyword is optional and you can also specify the alias directly after the class
name, as follows −
SELECT Clause
The SELECT clause provides more control over the result set then the from clause.
If you want to obtain few properties of objects instead of the complete object, use
the SELECT clause. Following is the simple syntax of using SELECT clause to get just
first_name field of the Employee object −
WHERE Clause
If you want to narrow the specific objects that are returned from storage, you use
the WHERE clause. Following is the simple syntax of using WHERE clause −
ORDER BY Clause
To sort your HQL query's results, you will need to use the ORDER BY clause. You
can order the results by any property on the objects in the result set either
ascending (ASC) or descending (DESC). Following is the simple syntax of using
ORDER BY clause −
String hql = "FROM Employee E WHERE E.id > 10 ORDER BY E.salary DESC";
Query query = session.createQuery(hql);List results = query.list();
If you wanted to sort by more than one property, you would just add the additional
properties to the end of the order by clause, separated by commas as follows −
GROUP BY Clause
This clause lets Hibernate pull information from the database and group it based on
a value of an attribute and, typically, use the result to include an aggregate value.
Following is the simple syntax of using GROUP BY clause −
UPDATE Clause
Bulk updates are new to HQL with Hibernate 3, and delete work differently in
Hibernate 3 than they did in Hibernate 2. The Query interface now contains a
method called executeUpdate() for executing HQL UPDATE or DELETE statements.
The UPDATE clause can be used to update one or more properties of an one or
more objects. Following is the simple syntax of using UPDATE clause −
DELETE Clause
The DELETE clause can be used to delete one or more objects. Following is the
simple syntax of using DELETE clause −
INSERT Clause
HQL supports INSERT INTO clause only where records can be inserted from one
object to another object. Following is the simple syntax of using INSERT INTO
clause −
Aggregate Methods
HQL supports a range of aggregate methods, similar to SQL. They work the same
way in HQL as in SQL and following is the list of the available functions −
1 avg(property name)
2 count(property name or *)
3 max(property name)
4 min(property name)
The distinct keyword only counts the unique values in the row set. The following
query will return only unique count −
This method takes an integer that represents the first row in your result set,
starting with row 0.
Using above two methods together, we can construct a paging component in our
web or Swing application. Following is the example, which you can extend to fetch
10 rows at a time −
query.setFirstResult(1);