0% found this document useful (0 votes)
28 views

Hibernate3.5 With JPA Presentation

The document provides an overview of Hibernate architecture. It discusses the key components of Hibernate architecture including the Session Factory, Session, Transaction Manager, and Query objects. The Session Factory encapsulates configuration properties and is used to create Session objects. Sessions are used to perform CRUD operations on persistent objects and are associated with a particular Transaction Manager. Queries can also be executed on the Session to retrieve data from the database. Hibernate provides an object/relational mapping layer of abstraction to handle object-relational impedance mismatch between object models and relational databases.

Uploaded by

ak8820
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Hibernate3.5 With JPA Presentation

The document provides an overview of Hibernate architecture. It discusses the key components of Hibernate architecture including the Session Factory, Session, Transaction Manager, and Query objects. The Session Factory encapsulates configuration properties and is used to create Session objects. Sessions are used to perform CRUD operations on persistent objects and are associated with a particular Transaction Manager. Queries can also be executed on the Session to retrieve data from the database. Hibernate provides an object/relational mapping layer of abstraction to handle object-relational impedance mismatch between object models and relational databases.

Uploaded by

ak8820
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 53

Hibernate Architecture

Learner

Session 1,2: Hibernate Architecture

© 2007, Cognizant Technology Solutions. All Rights Reserved.


The information contained herein is subject to change without notice.
C3: Protected
About the Author

Created By: Poonam Kamath(162321)

Credential 3 Years of experience


Information: Academy Products Team ( SCJP, SCWCD)
Version and HA /PPT/2011/1.0
Date:

2
Icons Used

Hands on
Questions Tools Exercise

Coding Test Your


Reference
Standards Understanding

A Welcome
Try it Out Contacts
Break

3
Hibernate Architecture Session 1, 2:
Overview
 Introduction: Automated and transparent
persistence, or exchange of objects between
the application and database. The components
are API for performing basic CRUD of
persistence classes, Query language/API,
facility to specify metadata, and technique for
interacting with transactional objects

4
Hibernate Architecture Session 1, 2 :
Objectives
 Objective:
Aftercompleting this chapter you will be able to:
»Explain ORM architecture
»Define the components in Hibernate Architecture
»Explain Annotations
»Create simple hibernate applications using mapping
file and annotations
» Explain the advantages of hibernate over JDBC
manual coding

5
Do You Know

 Basics of Java Bean components


 JDBC
» Creating JDBC application
» Performing Transaction over a JDBC connection
 SQL queries
 RDBMS concepts and usage of any RDBMS
product

6
Application Layered Architecture
 A typical Layered Architecture and its interface
dependencies

Presentation Layer

Utility
Business Layer and
Helper
Classes
Persistence Layer

7
Tabular Data vs. Domain Model
 Characteristics of applications that work with tabular
representation of persistent data:
» Applications work with tabular result sets in all layers
» Straightforward with JDBC and SQL
» Hard to code and configure the connection
» Re-usability of the code is limited
 Characteristics of applications that have an object-oriented
domain model:
» Application benefits from object-oriented techniques such as
inheritance, polymorphism, and design patterns
» Significant flexibility and reusability of business logic
» Greater degree of abstraction of the underlying relational data
» SQL / JDBC need not be hardcoded
» Certain operations (batch processing, reporting) are more tabular
in nature
 Some applications benefit from both, in different places

8
Paradigm Mismatch
 Classes implement the business entities of our
domain model
» Attributes of the entity are properties of our Java class
» Associations between entities are also implemented with
properties

BillingDetails
User
accountNumber: String
userName: String 1 1..*
accountName: String
address: String
accountType: String
billingDetails: Set
user: User

9
Paradigm Mismatch (Contd.)
 Tables mapped to the domain model

create table USER (


USER_NAME varchar not null primary
key,
ADDRESS varchar not null)

create table BILLING_DETAILS (


ACCOUNT_NUMBER varchar not null primary
key,
ACCOUNT_NAME varchar not null,
ACCOUNT_TYPE varchar not null,
USER_NAME varchar foreign key
references USER)

10
Problems Associated with Complex
O/R Model
 O/R paradigm poses mismatch problems as the complexity of
the domain model increases
 Example: Consider the following domain model that
incorporates inheritance and association between entities
» Representing the subtypes in a relational model makes the code
a little complex

1 *
User Billing Details

CreditCard Bank Account

11
Problems Associated with Complex
O/R Model (Contd.)
Accessing Entity Property Accessing Table column in
in JAVA SQL
userObject.getBillingDetails(). select * from USER u
getAccountName() left outer join
BILLING_DETAILS bd
[In Java, we "walk" the object on bd.USER_ID =
graph by following references] u.USER_ID
where u.USERNAME
= “paramesh“

[In SQL, we join tables to


get the required data]

12
Object Relational Mapping

 Object / Relational Mapping (ORM)


» solve the domain model to relational model
mismatch problem in middleware
» an ORM solution transforms data from the object-
oriented representation to the relational
representation
» metadata governs this transformation
 Object modeling describes a system through
objects that have identity, behavior, and
encapsulated state
» While Relational models describe a system by
information
• Tuples – pure data – no identity or state (Impedance
mismatch)

13
More on Object Relational Mapping

 Elements of an ORM implementation


» Object relational mapping is technique of mapping
the data representation from an object model to a
relational data model
• a programming model for the domain objects
• an API for performing CRUD operations
• a query language or other query facility
• a metadata facility
 Some ORM Framework
» JDO
» TopLink (Oracle)
» Hibernate
» iBatis
» EJB3

14
Hibernate as an ORM Framework
 Hibernate is an open source Object/Relational mapping
tool for Java
 It lets you develop persistent classes without caring
how to handle the data
 It relieves the developer from writing SQL queries which
forms 95% of common data persistence related
programming tasks
 Hibernate internally uses JDBC to connect to the
database
 “Write Once persist anywhere” - Hibernate allows
transparent persistence that enables the applications to
switch any database
 It is easier to build robust, high-performance database
applications with Java

15
ORM Framework

16
Usage of Hibernate

 Hibernate can be used in any kind of


Application Environment
 Every Database has its own session factory

Application Hibernate
Transaction
Transaction
EJB
EJB Manager
Manager
Session
Session

Session
Session Bean
Bean Transaction
Transaction
Resource
Resource
Standalone Manager
Manager
Standalone Query
Query

17
Hibernate Architecture

 Hibernate provides a layer of abstraction to the


application layer
 Persistent objects are the Java Bean components:
» They are a representation of the database records for the
application
» The application can perform operations like select, insert,
update and delete on the backend database with these
persistent objects

18
Hibernate Architecture (Contd.)
 Hibernate is configured to interact with the database
through the Hibernate Properties (hibernate.properties)
file and the XML mapping file
» The Properties file is a standard java properties file that
provides Hibernate information on: database connection
parameters, caching, persistent classes
» The Mapping file provide Hibernate with information to
persist objects to a relational database

Note: Certain applications use XML formatted Configuration file


( hibernate,cfg.xml) instead of properties file
Information provided in the XML Mapping file can be declared along
with the bean components as Annotations for higher versions of
Hibernate

19
Hibernate Architecture Component
 Session Factory (org.hibernate.SessionFactory)
» Encapsulates the properties listed in the hibernate configuration or
properties file
» Is created once, usually at the start of the application and is thread
safe
» Provides session objects to the application
» Compiled mapping for single database
» A factory for session
» A client of connection provider
» Might hold an optional (second-level) cache of data that is reusable
between transactions, at a process, or cluster-level

If both the hibernate.properties


and hibernate.cfg.xml files are
found in the application class
path, then hibernate.cfg.xml
overrides the settings found in
the hibernate.properties file

20
Hibernate Architecture Component
(Contd.)
 Session (org.hibernate.Session)
» Is required to work with the database
» Is Single threaded
» Is a single interface to the entire persistent layer from java
application
» Factory for transaction
» Holds first level cache for persistent objects
» It can be created, used and closed any number of times
» Is the conversation between a client and server
» Obtains a JDBC connection when needed
 Transaction (org.hibernate.Transaction)
» Is a series of operations that are executed as an atomic
operation
» Is obtained from the session object
» Is single threaded
» Abstracts application from underlying JDBC, JTA, or CORBA
transaction
» Transaction demarcation is mandatory

21
Annotations
 Annotations are powerful and easy way used to provide metadata
about the class to the compiler
 Hibernate incorporates JPA (JPA) to provide an Annotation support
from version 3.5
 The Java Persistence API (JPA) is a POJO persistence API for
object/relational mapping
» It contains a full object/relational mapping specification supporting the
use of Java language metadata annotations and/or XML descriptors to
define the mapping between Java objects and a relational database
 JPA annotations are in javax.persistance.* package
 Annotations can be split into two categories:
» Logical mapping annotations (describing the object model, the
association between two entities etc.)
» Physical mapping annotations (describing the physical schema, tables,
columns, indexes, etc)

22
JTA Transaction
 JDBC APIs are inefficient for transaction management in an environment
involving multiple databases or distributed databases
 It is here that Java Transaction APIs, JTA, come into the picture. What
really happens in the case of multiple databases is that a Transaction
Manager is required. And to communicate to the Transaction Manager, JTA
is required
» Transaction tcx=session.beginTransaction();
» The above statement instantiates transaction object, tcx
» Many instances of transaction can be retrieved using same session object as a
session (not class) can span many transactions (not classes)
» There are three implementations of the transaction interface provided by
Hibernate
a. JDBCTransaction
b. JTATransaction
c. CMTTransaction
» Of these, JDBCTransaction is the default i.e. if hibernate.transaction_factory
key’s value is not set in the hibernate.properties file, the transaction object
returned by the beginTransaction() method is the object of the JDBCTransaction
class

23
Hibernate JARS
 Unpack hibernate-distribution-3.5.5-Final and include
the jars from the lib file
» hsqldb.jar ------------ database jar if using hsqldb
» hibernate3.jar
» antlr-2.7.6.jar
» commons-collection-3.1.jar
» dom4j-1.6.1.jar
» javaasist-3.9.0.GA.jar
» jta.-1.1.jar
» log4j-1.2.14.jar
» slf4j-log4j12-1.6.0.jar
» slf4j-api-1.6.0.jar
» Hibernate-jpa-2.0-api-1.0.0.Final
 Include log4j.properties file in the class path
 NOTE: The required jars would be provided for the
training

24
hibernate.cfg.xml

<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:hsql://localhost</property>
<property name="connection.username">sa</property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<mapping class="bank.Account"/> <mapping
resource=“bank/account.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Explanation in the next slide

25
hibernate.cfg.xml (Contd.)
 To use Hibernate-provided JDBC connections, the configuration
file requires the following five properties:
» connection.driver_class -The JDBC connection class for the specific database
» connection.url -The full JDBC URL to the database
» connection.username -The username used to connect to the database
» connection.password - The password used to authenticate the username
» dialect -The name of the SQL dialect for the database
 The connection properties are common to any JDBC
 The dialect property tells Hibernate which SQL dialect to use for
certain operations
» Is used to ensure Hibernate Query Language (HQL) statements are correctly
converted into the proper SQL dialect for the underlying database.
 <mapping resource=“bank/account.hbm.xml"/>
» Mapping element provides the location and names of the mapping files
describing the persistent classes
 <mapping class="bank.Account"/>
» In higher versions of Hibernate the mapping element may contain the name of
the persistent class instead of the mapping file

26
Persistent Class
 These are bean classes that represent the database entities
frequented in the application
public class Employees { public Date getJoin_date() { Hibernate mapping File for the
return join_date; Employees bean class
public Employees() { }
super(); } public void setJoin_date(Date <?xml version="1.0"?>
int e_id; join_date) { <!DOCTYPE…………>
String first_name; this.join_date =
String last_name; join_date; <hibernate-mapping
double salary; } package="data">
Date join_date; public String getLast_name() { <class name="Employees"
public int getE_id() { return last_name; table="EmpTable">
return e_id; } <id name="e_id" />
} public void setLast_name(String <property name="first_name"
public void setE_id(int e_id) { last_name) { column="FNAME" />
this.e_id = e_id; this.last_name = <property name="last_name"
} last_name; column="LNAME"/>
public String getFirst_name() { } <property name="join_date"
return first_name; public double getSalary() { type="date"/>
} return salary; <property name="salary"
public void setFirst_name(String } type="double"/>
first_name ) { public void setSalary(double salary) </class>
this.first_name = { </hibernate-mapping>
first_name; this.salary = salary;
} }
}

27
Persistent Classes Specification

 Provide an ‘id’ property – not mandatory but


hibernate strongly recommends this – prefer
objects than primitives
 Prefer non-final classes – proxying
 Override equals() and hashCode() – if there
are associations – use ‘business key equality’
not by ‘ids’
 It should have a default Constructor (Package
level accessibility)
 All attributes that will be persisted should be
private and have a getter/setter methods (can
be private) defined in Java bean style

28
Hibernate Mapping File
 Named as EntityName.hbm.xml (Employees.hbm.xml) and
registered in hibernate.cfg.xml (Configuration)
 Mapping the class to the backend table:
<class name="Employees" table="EmpTable">……</class> EmpTable

e_id( primary FNAME LNAME join_date salary


key)

 Mapping a bean property to primary key: <id name="e_id" />


 Mapping the bean properties to columns of the table:
<property name="first_name" column="FNAME" />
<property name="last_name" column="LNAME"/>
<property name="join_date" type="date"/>
<property name="salary" type="double"/>
**FNAME, LNAME are the backend column names(optional) for the bean property first_name, last_name
**Specifying the type for columns is optional as Hibernate does an automatic type conversion from java
type to the specific database type
***NOTE: There are many other mapping elements that would be discussed in the consecutive chapters

29
Annotated Persistent class

import javax.persistence.*; public void setJoin_date(Date join_date) {


this.join_date = join_date;
@Entity }
@Table(name="EmpTable")
public class Employees { @Column(name="FNAME")
public String getFirst_name() {
public Employees() { return first_name;
super(); }
} public void setFirst_name(String first_name) {
int e_id; this.first_name = first_name;
String first_name; }
String last_name;
double salary; @Column(name="LNAME")
Date join_date; public String getLast_name() {
@Id return last_name;
public int getE_id() { }
return e_id; public void setLast_name(String last_name) {
} this.last_name = last_name;
public void setE_id(int e_id) { }
this.e_id = e_id;
} public double getSalary() {
public Date getJoin_date() { return salary;
return join_date; }
} public void setSalary(double salary) {
this.salary = salary;
} }

30
Annotated Persistent class
 JPAnnotations are used to define the ORM mappings in the
persistent class ( hibernate mapping file not required)
 @Entity annotation at the class level is to persist this class
with JPA
 @Table(name="EmpTable") used to specify a table name, if it
is different from the class name
 @Entity annotation, it is assumed that you will persist all
JavaBean properties to the database. For getter/setters of
Strings, primitives, and various number-related objects, we do
not have to do anything additional if we want to map to
columns with same name as the property
 @Id used to specify identifier/primary key
 @Column(name="FNAME") used to specify a column name, if
it is different from the property name
** multiple other annotation elements will be discussed in the
consecutive presentations

31
Demo: Basic Hibernate Application
with Mapping file
 The basic components required in a Hibernate Application:
» Java Persistent classes mapped to database tables
• If using JPA Annotations all the bean classes will be annotated with
metadata
» Hibernate mapping file XML file (bean_class.hbm.xml) that
maps bean properties to database tables
• If using JPA Annotations this file is not required
» Hibernate configuration file ( hibernate.cfg.xml) to configure
Hibernate SessionFactory
• Placed in the classpath
» Utility class (HibernateUtil.java)
• Singleton code that loads the SessionFactory object for the DAO
class
» DAO class that contains the code to perform database
operations with the Persistent object

32
Persistent Class and Hibernate
Mapping File
Employees.java Employees.hbm.xml
public class Employees { public Date getJoin_date() { Hibernate mapping File for the
return join_date; Employees bean class
public Employees() { }
super(); } public void setJoin_date(Date <?xml version="1.0"?>
int e_id; join_date) {
<!DOCTYPE…………>
String first_name; this.join_date =
String last_name; join_date;
} <hibernate-mapping
double salary;
public String getLast_name() { package="data">
Date join_date;
return last_name; <class name="Employees"
public int getE_id() {
return e_id; } table="EmpTable">
} public void setLast_name(String <id name="e_id" />
public void setE_id(int e_id) { last_name) { <property
this.e_id = e_id; this.last_name = name="first_name"
} last_name; column="FNAME" />
public String getFirst_name() { } <property
return first_name; public double getSalary() {
name="last_name"
} return salary;
column="LNAME"/>
public void setFirst_name(String }
public void setSalary(double <property
first_name ) {
salary) { name="join_date" type="date"/>
this.first_name =
this.salary = salary; <property name="salary"
first_name;
} } type="double"/>
} </class>
</hibernate-mapping>

33
hibernate.cfg.xml
<?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>
<!-- Database connection settings -->
<property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:hsql://localhost</property>
<property name="connection.username">sa</property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
<!-- Disable the second-level cache -->
<property
name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

34
hibernate.cfg.xml
<!-- Echo all executed SQL to stdout --> //Snapshot of the console output……//

<property name="show_sql">true</property> Hibernate:


<property name="format_sql">true</property> /* insert data.Employees
*/ insert
<property into
name="use_sql_comments">true</property> EmpTable
(FNAME, join_date, LNAME, salary, e_id)
values
<!-- Drop and re-create the database schema on (?, ?, ?, ?, ?)
Hibernate:
startup --> /*
<property name="hbm2ddl.auto">create</property> from
Employees */ select
<mapping resource="data/employees.hbm.xml"/> employees0_.e_id as e1_0_,
</session-factory> employees0_.FNAME as FNAME0_,
employees0_.join_date as join3_0_,
</hibernate-configuration> employees0_.LNAME as LNAME0_,
employees0_.salary as salary0_
from
EmpTable employees0_

 Hibernate properties:
» show_sql: displays SQL statements generated by hibernate on the console
» format_sql: generates a formatted SQL output
» use_sql_comments: includes comments along with the SQL statements
» generate_statistics: displays timestamp information with all SQL
statements executes at the backend
» hbm2dll.auto: if set to create, deletes the existing database schema and
creates new schema objects based on the mapping file, every time the
application is executed

35
HibernateUtil.java

package util;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from hibernate.cfg.xml
sessionFactory = new
Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {


return sessionFactory;
} }

36
DAO Class: EmployeesManage.java
 The DAO class provides package data;
functionality to list the tuples from import org.hibernate.Session;
the backend table and insert records import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
 Steps to communicate to the
import java.util.*;
backend
» Obtain the reference to the public class EmployeesManage{
Session factory (sf)
Generate a session object from the
Session factory (session)
public void list()
» Use the session object methods to {
Perform transactions at the backend SessionFactory sf=null;
(insert, update, delete) or view the tuples Session session=null;
from the backend (list) sf=util.HibernateUtil.getSessionFactory();
 Steps to list the tuples from the session=sf.openSession();
Backend List l1= session.createQuery("from
» createQuery(String hql) method of Employees").list();
Session object can be used with HQL as a for( int i=0;i<l1.size();i++)
Parameter returns a collection of {
instances ( tuples from backend)
Employees
» The collection can then be converted
into a list to iterate through each tuple
emp=(Employees)l1.get(i);
» Every instance in the collection is a type casted System.out.println(emp.getE_id()+"
to a bean component that is mapped to the tuples "+emp.getFirst_name()+"
» The getters are then used to view the "+emp.getLast_name()+"
properties of the bean (cell values of the tuples) "+emp.getJoin_date()+"
"+emp.getSalary());
}} 37
DAO Class: EmployeesManage.java
(Contd.)
public void insert(int e_id,String fname,String
 The DAO class snapshot that lname, double salary,Date join_date)
inserts records at the backend {
SessionFactory sf=null;
 Steps to communicate to the Session session=null;
backend ( remains same as stated earlier) Transaction tr=null;
 Steps to insert a tuple at the try{
backend sf=util.HibernateUtil.getSessionFactory();
» Obtain a transaction object from the session session=sf.openSession();
instance and begin the transaction tr=session.beginTransaction();
• All DML operations have to be executed within a Employees emp=new Employees();
Transaction boundary emp.setE_id(e_id);
» Create a new bean object(Employee) that is emp.setFirst_name(fname);
mapped to the backend table emp.setLast_name(lname);
» Call the setter methods of all the bean properties emp.setJoin_date(join_date);
With values that need to be inserted at the backend emp.setSalary(salary);
(the variables: e_id, fname, lname, salary, join_ session.save(emp);
date contain the values to be inserted at the backend) tr.commit();
» session.save(emp) associates the newly created }
emp object with the session. catch(Exception e){
• Whenever the session is closed or flushed it would System.out.println("Error with insert
be persisted at the backend block");
» tr.commit() persists the emp instance at the tr.rollback();
backend as a tuple session.close(); } } }

38
Client Code: Core Java Application
Interacting with Backend
 The client code can be:
» core java code, or a web component like JSP or Servlet, that uses
Hibernate Framework to interact with the backend
import data.Employees;
import data.EmployeesManage;
public class Client{
public static void main(String []a){
EmployeesManage em=new EmployeesManage();
em.insert(1001,"Smith","Morel",45000.0,new
Date());
em.insert(1002,"Sam","Morel",45000.0,new Date());
em.list();
}
}

» Records inserted at the backend


e_id FNAME LNAME join_date salary
1001 Smith Morel 2010-10-21 12:14:40.102 45000.0

1002 Sam Morel 2010-10-21 12:14:41.024 45000.0

39
JDBC vs Hibernate
 There is always a mismatch between how data is
represented in objects versus relational database
» With JDBC, developer has to write code to map an object
model's data representation to a relational data model and its
corresponding database schema
» Hibernate is flexible and powerful ORM solution to map Java
classes to database tables
• Hibernate itself takes care of this mapping using XML files or
metadata provided by annotations so developer need not write the
code
 Automatic mapping of Java objects with database tables and
vice versa is called Transparent Persistence
» Hibernate provides transparent persistence and developer does
not need to write code explicitly to map database table’s tuples
to application objects
» With JDBC this conversion is to be taken care of by the
developer manually

40
JDBC vs Hibernate (Contd.)
 Support for Query Language
» JDBC supports only native Structured Query
Language (SQL)
• Developer has to find out the efficient way to access
database, i.e to select effective query from a number of
queries to perform same task
» Hibernate provides a powerful query language
Hibernate Query Language (independent from type
of database) that is expressed in a familiar SQL like
syntax
• HQL includes full support for polymorphic queries
» Hibernate selects an effective way to perform a
database manipulation task for an application

41
JDBC vs Hibernate (Contd.)
 Database Dependent Code
» JDBC Applications tend to have database specific code
in large amount
• The code mostly comprises of mapping table data to
application objects and vice versa
• If the table or database is changed then it’s essential to
change object structure and the code
» Hibernate provides this mapping in specific XML files
• Thus a change in Database or table only need changes to
be made in XML file properties and /or persistent classes
*** NOTE: HQL will be discussed in detail in later presentations

42
JDBC vs Hibernate (Contd.)
 Maintenance Cost
» With JDBC, it is developer’s responsibility to handle JDBC result set and
convert it to Java objects, to use the persistent data in application
» Hibernate reduces lines of code by maintaining object-table mapping and
returns result to application in the form of Java objects.
• It relieves programmer from manual handling of persistent data, hence reducing
the development time and maintenance cost
 Optimize Performance
 Caching is retention of data, usually in application to reduce
disk access
» Hibernate allows applications to be configured to cache Result sets
• This improves performance if client applications read the same data multiple times
• Automatic Transparent Persistence allows the developer to concentrate more on
business logic rather than application code.
» With JDBC, caching is maintained by hand-coding
*** NOTE : Caching feature of hibernate is discussed in the Advance
Hibernate Course

43
JDBC vs Hibernate (Contd.)
 Automatic Versioning and Time Stamping
» By database versioning ensures that the changes done by one
person is not being roll backed by another
» Hibernate developer can define a version type property in the
persistent class mapped to a version field in the backend
• Hibernate updates version field of database table every time relational
tuple is updated by Java class object
» In JDBC there is no such checks during updates. The check has to
be added by the developer
 Open-Source, Zero-Cost Product License
» Hibernate is an open source and free to use for both development
and production deployments
 Hibernate applications provide Enterprise-Class Reliability and
Scalability
» JDBC can not be scaled easily

44
Some Drawbacks of Hibernate
 Hibernate adds an extra layer between the application and the
database. So the choice between Hibernate and JDBC has to
be gauged appropriately
 Use of Hibernate is an overhead for the applications which
are:
» Simple and use one database that never change
» Need to put data to database tables, no further SQL queries
 Support for Hibernate on Internet may sometimes be
insufficient
 For complex data, mapping from Object-to-tables and vise
versa reduces performance and increases time of conversion
 Hibernate does not allow some type of queries which are
supported by JDBC
» For example :It does not allow to insert multiple objects (persistent
data) to same table using single query. Developer has to write
separate query to insert each object

45
 Allow time for questions from participants

46
Tips
 Hibernate Architecture: Let Us Discuss Refer to
“Test_Annotation3.5” application to Moving from a Hibernate
mapping file to Annotations
 Moving from a Hibernate mapping file to Annotations
 List of changes to be done in the application
» Include additional jar
• hibernate-entitymanager.jar
• ejb3-persistence.jar
• hibernate-annotations.jar
• hibernate-commons-annotation.jar
• Hibernate-jpa-2.0-api-1.0.0.Final.jar

47
Tips (Contd.)
» Make changes in hibernate.cfg.xml file

<mapping resource="data/employees.hbm.xml"/>
To be replaced by
<mapping class="data.Employees"/>

» Make changes in HibaernateUtil.Java file


sessionFactory = new Configuration().configure().buildSessionFactory();
to be replaced by
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();

48
Hibernate Architecture: Let Us Discuss
» Make changes in the persistent class
import javax.persistence.*; public void setJoin_date(Date join_date) {
this.join_date = join_date;
@Entity }
@Table(name="EmpTable")
public class Employees { @Column(name="FNAME")
public String getFirst_name() {
public Employees() { return first_name;
super(); }
} public void setFirst_name(String first_name) {
int e_id; this.first_name = first_name;
String first_name; }
String last_name;
double salary; @Column(name="LNAME")
Date join_date; public String getLast_name() {
@Id return last_name;
public int getE_id() { }
return e_id; public void setLast_name(String last_name) {
} this.last_name = last_name;
public void setE_id(int e_id) { }
this.e_id = e_id;
} public double getSalary() {
public Date getJoin_date() { return salary;
return join_date; }
} public void setSalary(double salary) {
this.salary = salary;
} }

49
Test Your Understanding
1. Fill in the blanks:
Object relational mapping is technique of mapping the data
representation from an _________ model to a __________
data model.
2. Fill in the blanks:
_______displays SQL statements generated by hibernate on
the console
2. Fill in the blanks:
The ________ property tells Hibernate which SQL dialect to
use for certain operations.
Select answers from following:

dialect
Object
show_sql
Relational

50
Hibernate Architecture Session 1, 2 :
Summary
 Hibernate is one of the Leading ORM
frameworks in the market.
 It uses the open Source code managed by
JBOSS.
 It uses the object to RDBMS mappings.
 It supports almost all commonly used
databases
 Session Factory is used to create a Session
Object.
 The session object is used to interact with the
database

51
Hibernate Architecture Session 1, 2 :
Source
 http://docs.jboss.org/hibernate/stable/
annotations/reference/en/html/
entity.html#entity-mapping
 http://www.roseindia.net/hibernate/
hibernate_architecture.shtml
 http://www.developer.com/open/article.php/
3559931/Hibernate-Basics.htm
 http://www.mindfiresolutions.com/mindfire/
Java_Hibernate_JDBC.pdf

Disclaimer: Parts of the content of this course is based on the materials available from the Web sites and
books listed above. The materials that can be accessed from linked sites are not maintained by Cognizant
Academy and we are not responsible for the contents thereof. All trademarks, service marks, and trade names in
this course are the marks of the respective owner(s).

52
You have completed
Session 1,2 of
Hibernate
Architecture.

© 2007, Cognizant Technology Solutions. All Rights Reserved.


The information contained herein is subject to change without notice.

You might also like