SlideShare una empresa de Scribd logo
1 de 44
List of Topics
 What is Hibernate
 JDBC, ORM

 Hibernate Architecture
 Configuration
 Session

 Mapping
 Annotations
 HQL
 Caching
 Batch processing
 Interceptors
 Exercise
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
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.
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.
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
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.
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.
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
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
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.
Hibernate Architecture cont…
Detailed view of the Hibernate Application Architecture with few important
core classes.
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.
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.
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.
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
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.
Hibernate configuration cont…
 Sample file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Connection to Oracle db -->
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="hibernate.connection.username">test</property>
<property name="hibernate.connection.password">test123</property>
<!-- Auto commit to false -->
<property name="hibernate.connection.autocommit">false</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.use_sql_comments">true</property>
</session-factory>
</hibernate-configuration>
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.
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.
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.
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
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)
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
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
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.
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.
HQL cont…
 Pagination using query
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.
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();
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();
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.
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.
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>
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();
}
Caching cont…
 Cache provider:

 Sample hibernate config file with caching
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.
Caching cont…
 To use the query cache, you use the setCacheable(Boolean) method of

the Query class. For example:
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.
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:
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.
Interceptors cont…
 Following is the list of all the methods available within the Interceptor
interface:
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.
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/

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Hibernate
HibernateHibernate
Hibernate
 
Hibernate Basic Concepts - Presentation
Hibernate Basic Concepts - PresentationHibernate Basic Concepts - Presentation
Hibernate Basic Concepts - Presentation
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architecture
 
JPA For Beginner's
JPA For Beginner'sJPA For Beginner's
JPA For Beginner's
 
Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorial
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentation
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Introduction to Hibernate
Introduction to HibernateIntroduction to Hibernate
Introduction to Hibernate
 
Jpa
JpaJpa
Jpa
 
Spring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesSpring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutes
 
Java persistence api 2.1
Java persistence api 2.1Java persistence api 2.1
Java persistence api 2.1
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 

Destacado

Intro To Hibernate
Intro To HibernateIntro To Hibernate
Intro To HibernateAmit Himani
 
High dimesional data (FAST clustering ALG) PPT
High dimesional data (FAST clustering ALG) PPTHigh dimesional data (FAST clustering ALG) PPT
High dimesional data (FAST clustering ALG) PPTdeepan v
 
Document retrieval using clustering
Document retrieval using clusteringDocument retrieval using clustering
Document retrieval using clusteringeSAT Journals
 
Cluster Evaluation in Catalonia
Cluster Evaluation in Catalonia Cluster Evaluation in Catalonia
Cluster Evaluation in Catalonia TCI Network
 
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)ZFConf Conference
 
Object relationship mapping and hibernate
Object relationship mapping and hibernateObject relationship mapping and hibernate
Object relationship mapping and hibernateJoe Jacob
 
Proxy deep-dive java-one_20151027_001
Proxy deep-dive java-one_20151027_001Proxy deep-dive java-one_20151027_001
Proxy deep-dive java-one_20151027_001Sven Ruppert
 
Профессиональная разработка в суровом Enterprise
Профессиональная разработка в суровом EnterpriseПрофессиональная разработка в суровом Enterprise
Профессиональная разработка в суровом EnterpriseAlexander Granin
 
Orm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел ВейникOrm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел ВейникAlina Dolgikh
 
Classloading and Type Visibility in OSGi
Classloading and Type Visibility in OSGiClassloading and Type Visibility in OSGi
Classloading and Type Visibility in OSGimartinlippert
 
Hibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic IntroductionHibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic IntroductionEr. Gaurav Kumar
 
Java API for XML Web Services (JAX-WS)
Java API for XML Web Services (JAX-WS)Java API for XML Web Services (JAX-WS)
Java API for XML Web Services (JAX-WS)Peter R. Egli
 
Spring Framework - Validation
Spring Framework - ValidationSpring Framework - Validation
Spring Framework - ValidationDzmitry Naskou
 
AWS CloudFormation en 5 Minutos
AWS CloudFormation en 5 MinutosAWS CloudFormation en 5 Minutos
AWS CloudFormation en 5 MinutosOSOCO
 
Understanding Java Dynamic Proxies
Understanding Java Dynamic ProxiesUnderstanding Java Dynamic Proxies
Understanding Java Dynamic ProxiesOSOCO
 

Destacado (20)

Intro To Hibernate
Intro To HibernateIntro To Hibernate
Intro To Hibernate
 
Hibernate
HibernateHibernate
Hibernate
 
High dimesional data (FAST clustering ALG) PPT
High dimesional data (FAST clustering ALG) PPTHigh dimesional data (FAST clustering ALG) PPT
High dimesional data (FAST clustering ALG) PPT
 
Document retrieval using clustering
Document retrieval using clusteringDocument retrieval using clustering
Document retrieval using clustering
 
JAX-WS Basics
JAX-WS BasicsJAX-WS Basics
JAX-WS Basics
 
Cluster Evaluation in Catalonia
Cluster Evaluation in Catalonia Cluster Evaluation in Catalonia
Cluster Evaluation in Catalonia
 
Proxy & CGLIB
Proxy & CGLIBProxy & CGLIB
Proxy & CGLIB
 
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
 
Object relationship mapping and hibernate
Object relationship mapping and hibernateObject relationship mapping and hibernate
Object relationship mapping and hibernate
 
Proxy deep-dive java-one_20151027_001
Proxy deep-dive java-one_20151027_001Proxy deep-dive java-one_20151027_001
Proxy deep-dive java-one_20151027_001
 
Профессиональная разработка в суровом Enterprise
Профессиональная разработка в суровом EnterpriseПрофессиональная разработка в суровом Enterprise
Профессиональная разработка в суровом Enterprise
 
Dynamic Proxy by Java
Dynamic Proxy by JavaDynamic Proxy by Java
Dynamic Proxy by Java
 
Orm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел ВейникOrm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел Вейник
 
Classloading and Type Visibility in OSGi
Classloading and Type Visibility in OSGiClassloading and Type Visibility in OSGi
Classloading and Type Visibility in OSGi
 
Hibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic IntroductionHibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic Introduction
 
hibernate with JPA
hibernate with JPAhibernate with JPA
hibernate with JPA
 
Java API for XML Web Services (JAX-WS)
Java API for XML Web Services (JAX-WS)Java API for XML Web Services (JAX-WS)
Java API for XML Web Services (JAX-WS)
 
Spring Framework - Validation
Spring Framework - ValidationSpring Framework - Validation
Spring Framework - Validation
 
AWS CloudFormation en 5 Minutos
AWS CloudFormation en 5 MinutosAWS CloudFormation en 5 Minutos
AWS CloudFormation en 5 Minutos
 
Understanding Java Dynamic Proxies
Understanding Java Dynamic ProxiesUnderstanding Java Dynamic Proxies
Understanding Java Dynamic Proxies
 

Similar a Hibernate in Action

Free Hibernate Tutorial | VirtualNuggets
Free Hibernate Tutorial  | VirtualNuggetsFree Hibernate Tutorial  | VirtualNuggets
Free Hibernate Tutorial | VirtualNuggetsVirtual Nuggets
 
Hibernate Interview Questions
Hibernate Interview QuestionsHibernate Interview Questions
Hibernate Interview QuestionsMayank Kumar
 
Java hibernate orm implementation tool
Java hibernate   orm implementation toolJava hibernate   orm implementation tool
Java hibernate orm implementation tooljavaease
 
Hibernate Interview Questions | Edureka
Hibernate Interview Questions | EdurekaHibernate Interview Questions | Edureka
Hibernate Interview Questions | EdurekaEdureka!
 
Hibernate training at HarshithaTechnologySolutions @ Nizampet
Hibernate training at HarshithaTechnologySolutions @ NizampetHibernate training at HarshithaTechnologySolutions @ Nizampet
Hibernate training at HarshithaTechnologySolutions @ NizampetJayarajus
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer ReferenceMuthuselvam RS
 
Learn HIBERNATE at ASIT
Learn HIBERNATE at ASITLearn HIBERNATE at ASIT
Learn HIBERNATE at ASITASIT
 
Rollin onj Rubyv3
Rollin onj Rubyv3Rollin onj Rubyv3
Rollin onj Rubyv3Oracle
 
Hibernate Interview Questions and Answers
Hibernate Interview Questions and AnswersHibernate Interview Questions and Answers
Hibernate Interview Questions and AnswersAnuragMourya8
 
What is Hibernate Framework?
What is Hibernate Framework?What is Hibernate Framework?
What is Hibernate Framework?Ducat India
 
Hibernate jj
Hibernate jjHibernate jj
Hibernate jjJoe Jacob
 

Similar a Hibernate in Action (20)

What is hibernate?
What is hibernate?What is hibernate?
What is hibernate?
 
What is hibernate?
What is hibernate?What is hibernate?
What is hibernate?
 
Free Hibernate Tutorial | VirtualNuggets
Free Hibernate Tutorial  | VirtualNuggetsFree Hibernate Tutorial  | VirtualNuggets
Free Hibernate Tutorial | VirtualNuggets
 
What is hibernate?
What is hibernate?What is hibernate?
What is hibernate?
 
Hibernate Interview Questions
Hibernate Interview QuestionsHibernate Interview Questions
Hibernate Interview Questions
 
Java hibernate orm implementation tool
Java hibernate   orm implementation toolJava hibernate   orm implementation tool
Java hibernate orm implementation tool
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate.pdf
Hibernate.pdfHibernate.pdf
Hibernate.pdf
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate Interview Questions | Edureka
Hibernate Interview Questions | EdurekaHibernate Interview Questions | Edureka
Hibernate Interview Questions | Edureka
 
Hibernate training at HarshithaTechnologySolutions @ Nizampet
Hibernate training at HarshithaTechnologySolutions @ NizampetHibernate training at HarshithaTechnologySolutions @ Nizampet
Hibernate training at HarshithaTechnologySolutions @ Nizampet
 
Hibernate 3
Hibernate 3Hibernate 3
Hibernate 3
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer Reference
 
Learn HIBERNATE at ASIT
Learn HIBERNATE at ASITLearn HIBERNATE at ASIT
Learn HIBERNATE at ASIT
 
Rollin onj Rubyv3
Rollin onj Rubyv3Rollin onj Rubyv3
Rollin onj Rubyv3
 
Hibernate Interview Questions and Answers
Hibernate Interview Questions and AnswersHibernate Interview Questions and Answers
Hibernate Interview Questions and Answers
 
What is Hibernate Framework?
What is Hibernate Framework?What is Hibernate Framework?
What is Hibernate Framework?
 
Hibernate jj
Hibernate jjHibernate jj
Hibernate jj
 
Hibernate training-topics
Hibernate training-topicsHibernate training-topics
Hibernate training-topics
 
Hibernate
HibernateHibernate
Hibernate
 

Último

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 

Último (20)

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 

Hibernate in Action

  • 1.
  • 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.
  • 12. Hibernate Architecture cont… Detailed view of the Hibernate Application Architecture with few important core classes.
  • 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.
  • 18. Hibernate configuration cont…  Sample file <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Connection to Oracle db --> <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property> <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property> <property name="hibernate.connection.username">test</property> <property name="hibernate.connection.password">test123</property> <!-- Auto commit to false --> <property name="hibernate.connection.autocommit">false</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <property name="hibernate.use_sql_comments">true</property> </session-factory> </hibernate-configuration>
  • 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(); }
  • 36. Caching cont…  Cache provider:  Sample hibernate config file with caching
  • 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.
  • 42. Interceptors cont…  Following is the list of all the methods available within the Interceptor interface:
  • 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/