Beruflich Dokumente
Kultur Dokumente
Prerequisite
Knowledge of Relational Model and SQL
Object oriented concepts and implementation
Java programming language
References
Hibernate Reference Documentation
www.hibernate.org
Java Persistence with Hibernate Manning (Dreamtech)
publication
Hibernate Quickly - Manning (Dreamtech) publication
Introduction
Object relational mapping tool for java environment
Critical component of JBoss Enterprise Middleware
System (JEMS) suite of products.
Mapping of data representation from object model to a
relational model with a SQL based schema
Useful for object oriented domain model
Introduction
Persistence is the major challenge for any enterprise
application
Persistence can be achieved by using Entity Bean or
JDBC & stored procedure
Hibernate Open source ORM Framework which acts as
a bridge between application and database by storing
application objects in database
Paradigm Mismatch
Problem of Granularity
Problem of Subtype
Problem of Identity
Problem of Association
Problem of Data Navigation
Paradigm Mismatch..
Problem of Granularity:
Java objects can have several levels of granularity.
E.g. consider an association between classes like
User and Address.
Paradigm Mismatch..
Problem of Subtype:
Java objects implement inheritance for defining super-type/ subtype relationship.
Each sub or super class define different data and different
functionality.
There is no support of inheritance in SQL.
Problem of Identity:
Java provides two methods for checking equality of objects.
The == operator checks Object identity.
The equals() method checks object state equality (equality of value).
Paradigm Mismatch..
Problem of Association:
Associations define relation between entities.
In Java we can have polymorphic associations represented by
references where in relational world it is represented by foreign
keys.
Table association is only one to many or one to one
Paradigm Mismatch..
Problem of Data Navigation:
Difference in the way objects are accessed in Java and SQL.
In Java, we can have something like
currentUser.getAddress().getZipCode() to access the zip code
of the user.
In SQL, it can be done through SQL joins which are less efficient
and cumbersome.
Hibernate
Allows developers to focus on domain object modeling
not the persistence plumbing
Automated persistence of objects to relational table
Metadata for describing mapping between objects and
database
Additional cost for development ,compensated by less
overhead involved in maintenance
Sophisticated query facilities and caching
14
Advantages
Improved Productivity
Maintainability by ease towards changes
Improved Performance through object caching
Sophisticated query facilities like criteria API, Query by
example(QBE) , Hibernate query language(HQL)
Vendor independence Support for all type of relational
database
15
Distribution
Hibernate Core
Hibernate 3.2.x base service
Criteria Query and HQL support
Mapping metadata via XML mapping files
Hibernate Annotations
Use of jdk 5.0 metadata
Reduced Code
Hibernate EntityManager
Provides JPA compatability
Hibernate Architecture
Application
Persistence Objects
Hibernate
Hibernate Properties
Object.hbm.xml
Hibernate.cfg.xml
Database
17
Transient Objects
Persistent
Objects
Session Factory
Session
Transaction Factory
JNDI
Transaction
Connection Provider
JDBC
JTA
DATABASE
18
18
19
20
21
Instance States
Transient
The instance is not and has never been associated
with any session ( persistence context)
It has no persistence identity or primary key value
It has no corresponding row in database
e.g when POJO instance is created
Persistent
The instance is currently associated with a session
It has a persistence identity or primary key value
It has a corresponding row in database
e.g when POJO instance is peristed
22
22
Instance States
Detached
The instance was once associated with a persistence
context , but that context is closed or the instance was
serialized to another process
It has a persistence identity and perhaps a
corresponding row in database
Used when POJO object instance needs to be sent
over to another program for manipulation without
having persistent context
23
24
25
26
Lifecycle Operations
The instance states are affected by
Saving objects
Loading objects
Getting objects
Refreshing objects
Updating objects
Deleting objects
Querying objects
27
Lifecycle Operations
Saving object
An object remains in transient state until it is saved
and moved into persistent state
The class of the object that is being saved must have
a mapping file ( class.hbm.xml)
Generated event is
org.hibernate.event.SaveOrUpdateEvent
Method called save() from Session interface
Ex :
public Serializable save(Object object)
public void save(Object object, Serializable id)
28
Lifecycle Operations
Loading Objects
Used for loading objects from the database
load() requires objects primary key as identifier and
the identifier must be serializable
Returned object of type Object and needs to be typecasted to the domain class
Getting Object
Uses get() , works like load() method
Use load() when sure that object exists else throws
exception , whereas get() to be used if unsure about the
existence of object and it returns null if objects id is not
found in database.
29
Lifecycle Operations
Updating objects
Automatic manage of changes to persistent objects
flush() used to commit all changes to database
Deleting objects
Removes an object from database
Operation
SQL Command
save() or persist()
INSERT
delete()
DELETE
update() or merge ()
UPDATE
INSERT or UPDATE
30
32
CONFIGURATION
33
Programmatic Configuration
Sits on top of JDBC, for older versions take out the
followings from Hibernate configuration
hibernate.jdbc.batch_size=0
hibernate.jdbc.use_scrollable_resultsets=false
Support for JMX, JNDI HibernateServiceMBean and StatisticsService
NamingStrategyConfiguration cfg=new Configuration();
Cfg.setNamingStrategy(ImprovedNamingStrategy.INSTANCE)
Programmatic
Configuration instance of org.hibernate.cfg.configuration
Configuration cfg =new Configuration()
.addResource(Person.hbm.xml);
.addResource(Event.hbm.xml);
OR
Configuration cfg =new Configuration()
.addClass(com.myhibernate.Person.class)
. addClass(com.myhibernate.Event.class);
.setProperty(hibernate.dialect,org.hibernate.dialect.
Oracle9Dialect);
SessionFactory sf=cfg.buildSessionFactory();
//creating session from pool
35
JDBC Properties
hibernate.connection.driver_class jdbc driver class
hibernate.connection.url jdbc URL
hibernate.connection.username database user
hibernate.connection.password database user
password
hibernate.connection.pool_size maximum number of
pooled connections
36
DataSource properties
hibernate.connection.datasource datasource JNDI name
hibernate.jndi.url URL of the JNDI provider (optional)
hibernate.jndi.class class of the JNDI
InitialContextFactory (optional)
hibernate.connection.username database user
(optional)
hibernate.connection.password database user
password (optional)
37
Hibernate Types
Primitive or Wrappers
integer,long,short,float,double,character,byte,boolean
Other Classes
string
date,time,timestamp
calender,calender_date
big_decimal,big_integer
timezone,currency,class,text,serializable
clob and blob
41
Overview of mapping
SQL allows table without primary key but object always
needs unique identifier to distinguish
Lazy loading certain classes will only be loaded to
memory when required
43
Mapping relationships
Types
one-to-one Either end can be the owner (only one)
many-to-one Many end must be the owner
one-to-many Many end must be the owner
many-to-many Either end can be owner
Owner holds the foreign key referring to primary key of
other table in the association
44
PK Id
PK Id
userName
FK- userId
45
USER_Email
PK Id
PK,FK userId
PK Id
userName
PK,FK emailId
USER
One-To-Many Relationship
<set>
<list>
<array>
<bag>
47
48
51
54
60
61
Inheritance
3 different ways
One table per each concrete class implementation
One table for each subclass (including interfaces
and abstract classes)
One table for each class hierarchy
62
63
64
65
Annotations in Hibernate
66
Annotations
Annotation in Entity:import javax.persistence.*;
@Entity
public class Emp{
@Id
public Integer id;
..}
Creating sessionfactory
SessionFactory factory=
new AnnotationConfiguration().configure().buildSessionFactory();
Create configuration object
AnnotationConfiguration config=new AnnotationConfiguration();
config.addAnnotatedClass(Emp.class)
SessionFactory factory=config.configure().buildSessionFactory();
We enable you to leverage knowledge
anytime, anywhere!
@Id
@GeneratedValue
public int getId(){ return id; }
Sequence Generator
@id
@SequenceGenerator(name=s1, sequenceName=SEQ1)
@GeneratedValue(strategy=SEQUENCE, generator=s1)
We enable you to leverage knowledge
anytime, anywhere!
69
70
71
72
Restrictions
Add restrictions to the Criteria query object with add()
method
The add() method of the Criteria object takes an
org.hibernate.criterion.Criterion object that represents
an individual restriction
You can have more than one restriction for a Criteria
query
73
Restrictions.eq(name, Biswa)
Restrictions.ne(name, NoName)
Restrictions.like(name, Sa%)
Restrictions.ilike(name, sa%)
Restrictions.isNull(name);
Restrictions.gt(price,new Double(30.0))
Restrictions.between(age, new Integer(2), new
Integer(10))
Restrictions.or(criterion1, criterion2)
Restrictions.disjunction()
74
Add - Restriction
// Retrieve person objects whose name has a pattern
Criteria crit = sess.createCriteria(Person.class);
Criterion nameRestriction = Restrictions.like("name",
Biswa%");
crit.add( nameRestriction );
List results = crit.list();
75
76
Aggregate Functions
avg(String propertyName)
average of a property's value
count(String propertyName)
number of times a property has a value
countDistinct(String propertyName)
number of unique values the property contains
max(String propertyName)
min(String propertyName)
sum(String propertyName)
sum of the property values
77
78
79
80
81
from clause
Return all instances of the class eg.Cat
from eg.Cat
Usually don't need to qualify the class name, since autoimport is the default.
from Cat is same as from eg.Cat
82
Alias
Multiple classes may appear, resulting in a Cartesian
product or "cross" join.
from Formula, Parameter
from Formula as form, Parameter as param
Name query aliases using an initial lowercase ,consistent
with Java naming standards for local variables
83
join
We may also assign aliases to associated entities, or
even to elements of a collection of values, using a join
from Cat as cat
inner join cat.mate as mate
left outer join cat.kittens as kitten
from Cat as cat left join cat.mate.kittens as kittens
from Formula form full join form.parameter param
84
inner join
left outer join
right outer join
full join (not usually useful)
85
select clause
The select clause picks which objects and properties to
return in the query result set
select mate
from Cat as cat
inner join cat.mate as mate
Compact form
select cat.mate from Cat cat
86
select clause
Queries may return properties of any value type including
properties of component type
select cat.name from DomesticCat cat
where cat.name like 'fri%'
select cust.name.firstName from Customer as cust
Queries may return multiple objects and/or properties as
an array of type Object[ ]
select mother, offspr, mate.name from DomesticCat
as mother inner join mother.mate as mate left outer
join mother.kittens as offspr
87
select clause
Queries may return multiple objects and/or properties as
a List
select new list(mother, offspr, mate.name)
from DomesticCat as mother
inner join mother.mate as mate
left outer join mother.kittens as offspr
OR
as an actual typesafe Java object
select new Family(mother, mate, offspr)
from DomesticCat as mother join mother.mate as
mate left join mother.kittens as offspr
88
where clause
The where clause allows you to narrow the list of
instances returned.
If no alias exists, you may refer to properties by name
from Cat where name='Fritz'
If there is an alias, use a qualified property name:
from Cat as cat where cat.name='Fritz'
89
where clause
Return all instances of Foo for which there exists an
instance of bar with a date property equal to the
startDate property of the Foo
select foo
from Foo foo, Bar bar
where foo.startDate = bar.date
Compound path expressions make the where clause
extremely powerful.
from Cat cat where cat.mate.name is not null
90
Thank You
91