2. List of Topics
What is Hibernate
JDBC, ORM
Hibernate Architecture
Configuration
Session
Mapping
Annotations
HQL
Caching
Batch processing
Interceptors
Exercise
3. What is Hibernate ?
Hibernate is a high-performance Object/Relational persistence and query
service which is licensed under the open source GNU Lesser General Public
License (LGPL) and is free to download. 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.
It officially maintained by JBoss Inc., started in 2001
4. JDBC
What is JDBC?
JDBC stands for Java Database Connectivity and provides a set of Java API for
accessing the relational databases from Java program. These Java APIs enables
Java programs to execute SQL statements and interact with any SQL compliant
database.
JDBC API standard provides Java developers to interact with different RDBMS
and access table data through Java application without learning RDBMS details
and using Database Specific JDBC Drivers.
JDBC Architecture
When a Java application needs to access database:
open connection to database,
use JDBC driver to send SQL queries to database,
process the results that are returned, and
close the connection.
5. 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.
An ORM system has following advantages over plain JDBC
S.N.
Advantages
1
Lets business code access objects rather than DB tables.
2
Hides details of SQL queries from OO logic.
3
No need to deal with the database implementation.
4
Entities based on business concepts rather than database
structure.
5
Transaction management
6
Fast development of application.
6. Java ORM framework
There are several persistent frameworks and ORM options in Java. A
persistent framework is an ORM service that stores and retrieves
objects into a relational database.
Enterprise JavaBeans Entity Beans
Java Data Objects
Castor
TopLink
Spring DAO
Hibernate
And many more
7. Difference between Hibernate and JDBC
JDBC
Hibernate
JDBC is a persistence technology
Hibernate is a persistence Framework.
In JDBC developer is responsible to taking and
closing the connection and also write the SQL
statement.
In Hibernate HRS(Hibernate Runtime System) is
responsible for taking the connections, creating the
statement and releasing the connections.
As table changed or database changed then it’s
essential to change object structure as well as to
change code written to map table-to-object/objectto-table.
The actual mapping between tables and application
objects is done in XML files. If there is change in
Database or in any table then the only need to
change XML file properties.
Low performance and not scalable
High performance and scalable
it is developer’s responsibility to handle JDBC result
set and convert it to Java objects through code to use
this persistent data in application.
Hibernate reduces lines of code by maintaining
object-table mapping itself and returns result to
application in form of Java objects.
8. Hibernate overview
Hibernate is an Object-Relational Mapping(ORM) solution for JAVA and it raised as an
open source persistent framework created by Gavin King in 2001. It is a powerful, high
performance Object-Relational Persistence and Query service for any Java Application.
Hibernate maps Java classes to database tables and from Java data types to SQL data types
and relieve the developer from 95% of common data persistence related programming
tasks.
Hibernate sits between traditional Java objects and database server to handle all the work
in persisting those objects based on the appropriate O/R mechanisms and patterns.
9. Hibernate overview cont…
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 Database or in any table then the only need to change
XML file properties.
Abstract away the unfamiliar SQL types and provide us to work around
familiar Java Objects.
Hibernate does not require an application server to operate.
Manipulates Complex associations of objects of your database.
Provides Simple querying of data
10. Hibernate overview cont…
Supported Databases:
Hibernate supports almost all the major RDBMS. Following is list of few of the database
engines supported by Hibernate.
HSQL Database Engine
DB2/NT
MySQL
PostgreSQL
FrontBase
Oracle
Microsoft SQL Server Database
Sybase SQL Server
Informix Dynamic Server
11. Hibernate Architecture
The Hibernate architecture is layered to keep you isolated from having to know
the underlying APIs. Hibernate makes use of the database and configuration
data to provide persistence services (and persistent objects) to the application.
13. Hibernate Architecture cont…
Hibernate uses various existing Java APIs, like JDBC, Java Transaction API(JTA),
and Java Naming and Directory Interface (JNDI). JDBC provides a rudimentary
level of abstraction of functionality common to relational databases, allowing
almost any database with a JDBC driver to be supported by Hibernate. JNDI
and JTA allow Hibernate to be integrated with J2EE application servers.
Following section gives brief description of each of the class objects involved in
Hibernate Application Architecture.
Configuration Object:
The Configuration object is the first Hibernate object you create in any
Hibernate application and usually created only once during application
initialization. It represents a configuration or properties file required by the
Hibernate. The Configuration object provides two keys components:
Database Connection: This is handled through one or more configuration
files supported by Hibernate. These files
are hibernate.properties and hibernate.cfg.xml.
Class Mapping Setup
This component creates the connection between the Java classes and database
tables.
14. Hibernate Architecture cont…
SessionFactory Object:
Configuration object is used to create a SessionFactory object which in turn
configures Hibernate for the application using the supplied configuration file
and allows for a Session object to be instantiated. The SessionFactory is a thread
safe object and used by all the threads of an application.
The SessionFactory is heavyweight object so usually it is created during
application start up and kept for later use. You would need one SessionFactory
object per database using a separate configuration file. So if you are using
multiple databases then you would have to create multiple SessionFactory
objects.
Session Object:
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.
15. Hibernate Architecture cont…
Transaction Object:
A Transaction represents a UOW (unit of work) with the
database and most of the RDBMS supports transaction
functionality. Transactions in Hibernate are handled by an
underlying transaction manager and transaction (from JDBC
or JTA).
Query Object:
Query objects use SQL or Hibernate Query Language (HQL)
string to retrieve data from the database and create objects.
String hql = "FROM Employee";
Query query = session.createQuery(hql);
Criteria Object:
Criteria object are used to create and execute object oriented
criteria queries to retrieve objects.
16. Hibernate Environment setup
Downloading Hibernate:
Download the latest version of
Hibernate http://www.hibernate.org/downloads
Hibernate Prerequisites
S.N. Packages/Libraries
1
dom4j - XML parsing www.dom4j.org/
2
Xalan - XSLT Processor http://xml.apache.org/xalan-j/
3
Xerces - The Xerces Java Parser http://xml.apache.org/xerces-j/
4
cglib - Appropriate changes to Java classes at
runtime http://cglib.sourceforge.net/
5
log4j - Logging Framework http://logging.apache.org/log4j
6
Commons - Logging, Email etc. http://jakarta.apache.org/commons
7
SLF4J - Logging Facade for Java http://www.slf4j.org
17. Hibernate Configuration
Hibernate requires to know in advance where to find the mapping information that
defines how your Java classes relate to the database tables. Hibernate also requires a set of
configuration settings related to database and other related parameters. All such
information is usually supplied as a standard Java properties file
called hibernate.properties, or as an XML file named hibernate.cfg.xml.
19. 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:
transient: A new instance of a persistent class which is not associated with
a Session and has no representation in the database and no identifier value
is considered transient by Hibernate.
persistent: You can make a transient instance persistent by associating it
with a Session. A persistent instance has a representation in the database,
an identifier value and is associated with a Session.
detached: Once we close the Hibernate Session, the persistent instance
will become a detached instance.
20. Sessions cont…
A typical transaction should use the following idiom:
Session session = factory.openSession();
Transaction tx = null;
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.
21. Persistence class
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 Java classes that will be persisted need a default no-argument, constructor.
All classes should contain an ID in order to allow easy identification of your objects
within Hibernate and the database. This property maps to the primary key column of a
database table.
All attributes that will be persisted should be declared private and
have getXXX and setXXXmethods defined in the JavaBean style.
All classes that do not extend or implement some specialized classes and interfaces.
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.
22. Hibernate with MySQL DB
MySQL is one of the most popular open-source database systems available
today.
Let us create hibernate.cfg.xml configuration file and place it in the root
of your application's classpath. You would have to make sure that you
have testdb database available in your MySQL database and you have a
user test available to access the database.
The XML configuration file must conform to the Hibernate 3 Configuration
DTD (document type definition) , which is available from
http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd.
Sample hibernate
23. Hibernate Mapping files
An Object/relational mappings are usually defined in an XML document. This
mapping file instructs Hibernate how to map the defined class or classes to the
database tables.
Let us consider POJO class whose objects will persist in the table defined in
next section (see attached Employee class)
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(see attached sql query for creating 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. (see attached mapping file)
24. Hibernate O/R mapping
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.
Mapping type
Description
Many-to-One
Mapping many-to-one relationship
One-to-One
Mapping one-to-one relationship
One-to-Many
Mapping one-to-many relationship
Many-to-Many
Mapping many-to-many relationship
25. Annotations
So far We have seen how Hibernate uses XML mapping file for the
transformation of data from POJO to database tables and vice versa.
Hibernate annotations is the newest way to define mappings without a
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.
Environment Setup for Hibernate Annotation
First of all you would have to make sure that you are using JDK
5.0 otherwise you
need to upgrade your JDK to JDK 5.0 to take advantage of the native support for
annotations.
Second, you will need to install the Hibernate 3.x annotations distribution package,
available from the source forge:
(http://sourceforge.net/projects/hibernate/files/hibernate-annotations/) and
copy hibernate-annotations.jar, lib/hibernate-comonsannotations.jar and lib/ejb3-persistence.jar from the Hibernate Annotations
distribution to your CLASSPATH
26. Annotation cont..
@Entity Annotation:
The EJB 3 standard annotations are contained in
the javax.persistence package, 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
@Table Annotation:
allows you to specify the details of the table that will be used to persist the
entity in the database.
@Id and @GeneratedValue Annotations:
Each entity bean will have a primary key, which you annotate on the class with
the @Id annotation. The primary key can be a single field or a combination of
multiple fields depending on your table structure.
The @GeneratedValue annotation is used to specify the primary key
generation strategy to use. If the strategy is not specified by default AUTO will
be used.
@Column Annotation:
is used to specify the details of the column to which a field or property will be
mapped.
27. Hibernate Query Language
Hibernate Query Language (HQL) is an object-oriented query language,
similar to SQL, but instead of operating on tables and columns, HQL works
with persistent objects and their properties. HQL queries are translated by
Hibernate into conventional SQL queries which in turns perform action on
database.
29. Criteria query
Hibernate provides alternate ways of manipulating objects and in turn data available in
RDBMS tables. One of the methods is Criteria API which allows you to build up a criteria
query object programmatically where you can apply filtration rules and logical
conditions.
The Hibernate Session interface provides createCriteria() method which can be used
to create a Criteria object that returns instances of the persistence object's class when
your application executes a criteria query.
30. Native SQL
Hibernate 3.x allows you to specify handwritten SQL, including stored
procedures, for all create, update, delete, and load operations.
Your application will create a native SQL query from the session with
the createSQLQuery() method on the Session interface.:
API
public SQLQuery createSQLQuery(String sqlString) throws HibernateException
Syntax :
Query query = session.createSQLQuery( "select * from stock s where s.stock_code =
:stockCode")
.addEntity(Stock.class)
.setParameter("stockCode", "7277");
List result = query.list();
31. Native SQL cont…
Named SQL queries:
The following is the syntax to get entity objects from a native sql query
via addEntity() and using named SQL query.
String sql = "SELECT * FROM EMPLOYEE WHERE id = :employee_id";
SQLQuery query = session.createSQLQuery(sql);
query.addEntity(Employee.class);
query.setParameter("employee_id", 10);
List results = query.list();
32. Caching
Caching is all about application performance optimization and it sits between
your application and the database to avoid the number of database hits as
many as possible to give a better performance for performance critical
applications.
33. Caching cont…
First-level cache:
Always associates with the Session object. Hibernate uses this cache by default.
Its easy to understand the first level cache if we understand the fact that it is associated with
Session object. As we know session object is created on demand from session factory and it is lost,
once the session is closed. Similarly, first level cache associated with session object is available
only till session object is live. It is available to session object only and is not accessible to any other
session object in any other part of application.
When we query an entity first time, it is retrieved from database and stored in first level cache
associated with hibernate session. If we query same object again with same session object, it will
be loaded from cache and no sql query will be executed.
The loaded entity can be removed from session using evict() method. The next loading of this
entity will again make a database call if it has been removed using evict() method.
The whole session cache can be removed using clear() method. It will remove all the entities
stored in cache.
34. Caching cont…
Second-level cache:
Always associates with sessionFactoryObject and is available to be used in all sessions which
are created using that particular session factory. It also means that once session factory is closed,
all cache associated with it die. It is responsible for caching objects across sessions. When this is
turned on, objects will first be searched in cache and if they are not found, a database query will
be fired.
Second level cache is an optional cache and first-level cache will always be consulted before any
attempt is made to locate an object in the second-level cache. If Entity is not present in either 1st
or 2nd level cache so, it is fetched from database.
Any third-party cache can be used with Hibernate.
An org.hibernate.cache.CacheProvider interface is provided, which must be implemented to
provide Hibernate with a handle to the cache implementation.
How to enable it?
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
35. Caching cont…
How to disable second level cache?
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
Example:
Using two sessions. We load the object in the first session, update it then load it in the second session. Both sessions
are created upfront and are kept open until the end.
public void complexLoad (){
Session session1 = getSessionFactory().openSession();
Session session2 = getSessionFactory().openSession();
Transaction tx1 = session1.beginTransaction();
Person p1 = (Person) session1.load(Person.class, 1L);
System.out.println (p1.getFirstName());
p1.setFirstName ("" + System.currentTimeMillis());
tx1.commit();
Transaction tx2 = session2.beginTransaction();
Person p2 = (Person)session2.load(Person.class, 1L);
System.out.println (p2.getFirstName());
tx2.commit();
session1.close();
session2.close();
}
37. Caching cont…
Query-level cache:
Hibernate also implements a cache for query result sets that integrates closely with
the second-level cache.
This is an optional feature and requires two additional physical cache regions that
hold the cached query results and the timestamps when a table was last updated.
This is only useful for queries that are run frequently with the same parameters.
To use the query cache, you must first activate it using
the hibernate.cache.use_query_cache="true“ property in the configuration file. By setting this
property to true, you make Hibernate create the necessary caches in memory to hold the query and
identifier sets.
38. Caching cont…
To use the query cache, you use the setCacheable(Boolean) method of
the Query class. For example:
39. Batch Processing
Consider a situation when you need to upload a large number of records into
your database using Hibernate. Following is the code snippet to achieve this
using Hibernate:
Session session = SessionFactory.openSession();
Transaction tx = session.beginTransaction();
for ( int i=0; i<100000; i++ ) {
Employee employee = new Employee(.....);
session.save(employee);
}
tx.commit();
session.close();
By default, Hibernate will cache all the persisted objects in the session-level cache
and ultimately your application will throw an OutOfMemoryException somewhere
around the 50,000th row. You can resolve this problem if you are using batch
processing with Hibernate.
40. Batch processing cont…
To use the batch processing feature, first set hibernate.jdbc.batch_size as
batch size to a number either at 20 or 50 depending on object size. This will tell
the hibernate container that every X rows to be inserted as batch. To
implement this in your code we would need to do little modification as follows:
<property name="hibernate.jdbc.batch_size"> 50 </property> add in config file
Code snippet:
41. Interceptors
Hibernate has a powerful feature called ‘interceptor‘ to intercept or hook
different kind of Hibernate events, like database CRUD operation.
As you have learnt that in Hibernate, an object will be created and
persisted. Once the object has been changed, it must be saved back to the
database. This process continues until the next time the object is needed,
and it will be loaded from the persistent store.
Thus an object passes through different stages in its life cycle
and Interceptor Interface provides methods which can be called at
different stages to perform some required tasks. These methods are
callbacks from the session to the application, allowing the application to
inspect and/or manipulate properties of a persistent object before it is
saved, updated, deleted or loaded.
How to use Interceptors?
To build an interceptor you can either implement Interceptor class
directly or extend EmptyInterceptorclass.
43. Disadvantage of Hibernate
It doesn’t allow some types of queries which are supported by JDBC.
For e.g. it does not allow to insert multiple objects to same table using
single query. Developer has to write a separate query to insert each
object.
Debugging: Sometimes debugging and performance tuning becomes
difficult.
44. Hibernate Examples
Hibernate with MySQL
http://www.tutorialspoint.com/hibernate/hibernate_examples.htm
Hibernate with Oracle
http://www.mkyong.com/hibernate/maven-3-hibernate-3-6-oracle-11gexample-xml-mapping/