You are on page 1of 91

HIBERNATE

Prerequisite
Knowledge of Relational Model and SQL
Object oriented concepts and implementation
Java programming language

We enable you to leverage knowledge


anytime, anywhere!

References
Hibernate Reference Documentation
www.hibernate.org
Java Persistence with Hibernate Manning (Dreamtech)
publication
Hibernate Quickly - Manning (Dreamtech) publication

We enable you to leverage knowledge


anytime, anywhere!

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

We enable you to leverage knowledge


anytime, anywhere!

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

We enable you to leverage knowledge


anytime, anywhere!

Object and Relation Model - Mismatch


In object model separate class may be needed while in
relational model data can be put in single or multiple
column in particular table e.g. User and Address
Data type supported in object model may differ from data
type supported in relational model
Object model supports inheritance but relational model ,
tables are individual entities.

We enable you to leverage knowledge


anytime, anywhere!

Object and Relation Model-Mismatch


Relational model relationship is maintained by foreign
key and used to identify single table. No way to identify
multiple tables by foreign key.
Two non identical objects can be checked for equality
whereas in relational model these can be represented as
the same row in table.

We enable you to leverage knowledge


anytime, anywhere!

Paradigm Mismatch
Problem of Granularity
Problem of Subtype
Problem of Identity
Problem of Association
Problem of Data Navigation

We enable you to leverage knowledge


anytime, anywhere!

Paradigm Mismatch..
Problem of Granularity:
Java objects can have several levels of granularity.
E.g. consider an association between classes like
User and Address.

We enable you to leverage knowledge


anytime, anywhere!

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).

In SQL, equality of two records are determined by the primary


key values.
Two or more objects can represent same row of data.
We enable you to leverage knowledge
anytime, anywhere!

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

We enable you to leverage knowledge


anytime, anywhere!

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.

We enable you to leverage knowledge


anytime, anywhere!

Current Persistence Options


SQL and JDBC
What impact if requirement changes ?
DAO Supporting technology for Hibernate
Serialization
Can data be retrieved without de serialization?
Impossible to access single object or subset of objects
Unsuitable for concurrent application support
ORM Tools
Hibernate , Oracle Toplink etc.
13

We enable you to leverage knowledge


anytime, anywhere!

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

We enable you to leverage knowledge


anytime, anywhere!

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

We enable you to leverage knowledge


anytime, anywhere!

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

We enable you to leverage knowledge


anytime, anywhere!

Hibernate Architecture
Application

Persistence Objects

Hibernate
Hibernate Properties

Object.hbm.xml

Hibernate.cfg.xml

Database

17

We enable you to leverage knowledge


anytime, anywhere!

Hibernate Architecture A Detail look


APPLICATION

Transient Objects

Persistent
Objects

Session Factory
Session
Transaction Factory

JNDI

Transaction

Connection Provider

JDBC

JTA

DATABASE

18

We enable you to leverage knowledge


anytime, anywhere!

Transient Objects Not associated with session


Persistent Objects Associated with one session ( javabeans /POJO)
Session Factory Factory for session and a client between connection Provider
Transaction Single threaded object to specify single atomic unit of work, abstract
applications from underlying JDBC or JTA transaction.
Session can be associated with no of transactions.
Connection Provider A factory or pool of JDBC connections, abstract applications
from underlying datastore or DriverManager

18

Hibernate Framework Objects


SessionFactory
Represented by org.hibernate.SessionFactory class
A factory of session
A client of ConnectionProvider
A threadsafe(immutable) cache of compiled mappings
for a single database
May hold second level cache(optional) which is
reusable between transactions at a process or clusterlevel

19

We enable you to leverage knowledge


anytime, anywhere!

Hibernate Framework Objects


Session
Represented by org.hibernate.Session
A single threaded, short lived object representing a
conversation between the application and persistence
store
Wraps JDBC connection
Factory of Transaction
Holds a mandatory first level cache of persistent
objects, used when navigating the object graph or
looking up objects by identifier

20

We enable you to leverage knowledge


anytime, anywhere!

Hibernate Framework Objects


Persistent objects and collections
Short lived, single threaded objects containing
persistent state and business function
Ordinary javabeans/POJO and are associated with
exactly one Session
Changes made to persistent objects are reflected to
the database tables when committed
Once session is closed , they will be detached and
free to use in any application layer like data transfer
objects to and from presentation

21

We enable you to leverage knowledge


anytime, anywhere!

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

We enable you to leverage knowledge


anytime, anywhere!

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

We enable you to leverage knowledge


anytime, anywhere!

Hibernate Framework Objects


Transaction
Represented by org.hibernate.Transaction
A single threaded, short lived object used by the
application to specify atomic unit of work
Abstracts application from underlying JDBC , JTA or
CORBA transaction
A session might span several transactions in some
cases
Transaction demarcation, either using the underlying
API or Transaction is never optional

24

We enable you to leverage knowledge


anytime, anywhere!

Hibernate Framework Classes


ConnectionProvider
Represented by
org.hibernate.connection.ConnectionProvider
A factory for(pool of) JDBC connections
Abstracts application from underlying DataSource or
DriverManager
Not exposed to application but can be extended or
implemented by the developer

25

We enable you to leverage knowledge


anytime, anywhere!

Hibernate Framework Classes


TransactionFactory
Represented by org.hibernate.TransactionFactory
A factory for Tranasaction instances
Not
exposed
to
application
but
can
be
extended/implemented by developer

26

We enable you to leverage knowledge


anytime, anywhere!

Lifecycle Operations
The instance states are affected by
Saving objects
Loading objects
Getting objects
Refreshing objects
Updating objects
Deleting objects
Querying objects

27

We enable you to leverage knowledge


anytime, anywhere!

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

We enable you to leverage knowledge


anytime, anywhere!

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

We enable you to leverage knowledge


anytime, anywhere!

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

saveOrUpdate() & replicate()

INSERT or UPDATE

30

We enable you to leverage knowledge


anytime, anywhere!

Transaction & Locking


Session session=factory.openSesssion();
Transaction tx=null;
try{
tx=session.beginTransaction();
//life cycle operations
tx.commit();tx=null;
}catch(HibernateException e){
if(tx !=null) tx.rollback();
}finally{
session.close();
}
31

We enable you to leverage knowledge


anytime, anywhere!

Persistence Classes - POJO


Persistence classes is of type POJO and should follow
the following rules: Implement a no-argument constructor
Provide an identifier property (optional)
Declare accessors and mutators for persistent fields
(optional)
override the equals() and hashCode() methods

32

We enable you to leverage knowledge


anytime, anywhere!

CONFIGURATION

33

We enable you to leverage knowledge


anytime, anywhere!

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)

We enable you to leverage knowledge


anytime, anywhere!

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

We enable you to leverage knowledge


anytime, anywhere!

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

We enable you to leverage knowledge


anytime, anywhere!

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

We enable you to leverage knowledge


anytime, anywhere!

Optional Configuration Properties


hibernate.dialect The classname of a Hibernate Dialect
which allows Hibernate to generate SQL optimized for a
particular relational database.
hibernate.show_sql  Write all SQL statements to
console.
hibernate.connection.provider_class  The classname
of a custom ConnectionProvider which provides JDBC
connections to Hibernate
hibernate.cache.provider_class  The classname of a
custom CacheProvider.
hibernate.hbm2ddl.autoAutomatically
validate
or
export schema DDL to the database when the
SessionFactory is created.(update | create | create-drop)
38

We enable you to leverage knowledge


anytime, anywhere!

Key Generation Scheme


Increment
Generates identifier of type long, short or int that are
unique when no process is inserting data to same
table.
Assigned
Application assigns an identifier to object before
save() is called. Default strategy when no generator
specified
Native
It picks identity, sequence or hilo depending upon the
capabilities of the underlying database
Others hilo, seqhilo,sequence etc.
39

We enable you to leverage knowledge


anytime, anywhere!

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

We enable you to leverage knowledge


anytime, anywhere!

O/R Mapping- Relations

41

We enable you to leverage knowledge


anytime, anywhere!

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

We enable you to leverage knowledge


anytime, anywhere!

Hibernate Mapping Files


Object Relational mapping defined in XML document
Mapping documents are readable and hand-editable
Mapping language in java-centric, mapping constructed
around persistent classes not table declaration
Can use tool like XDoclet and annotation
Define
identifier
generation,
properties,
object
relationship ..

43

We enable you to leverage knowledge


anytime, anywhere!

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

We enable you to leverage knowledge


anytime, anywhere!

One to One Relationship


Expresses a relationship between two classes where
each instance of the first class is related to a single
instance of the second or vice versa
Can be expressed in the database in two ways
All data can be represented in single table
Giving each of the respective tables the same primary
key values
Using foreign key constraint from one table onto a
unique identifier column of the other
Email
USER

PK Id

PK Id

email

userName

FK- userId

45

We enable you to leverage knowledge


anytime, anywhere!

One-to-Many and Many-to-one Association


Representation
By foreign key, with no additional constraints
Link table by maintaining foreign key into each of
associated tables
Unique constraint to be specified on the one side of
relation (one to many) else it will be many to many

USER_Email

Email

PK Id

PK,FK userId

PK Id

userName

PK,FK emailId

email

USER

We enable you to leverage knowledge


anytime, anywhere!

One-To-Many Relationship

<set>
<list>
<array>
<bag>

47

We enable you to leverage knowledge


anytime, anywhere!

1.One to Many :Using <set>


Event has many speakers and attendees
<class name="Event" table="events">
<id name="id" column="uid" type="long"
unsaved-value="null">
<generator class="increment"/>
</id>
<property name="name" type="string" length="100"/>

48

We enable you to leverage knowledge


anytime, anywhere!

1.One to Many :Using <set>


Event has many speakers and attendees
<set name="speakers" cascade="all">
<key column="event_id"/>
<one-to-many class="Speaker"/>
</set>
<set name="attendees" cascade="all">
<key column="event_id"/>
<one-to-many class="Attendee"/>
</set>
</class>
49

We enable you to leverage knowledge


anytime, anywhere!

One to Many relationship: Creating Object Instance


Event has many speakers and attendees
public class Event {
private Long id;
private String name;
private Date startDate;
private int duration;
// Event has one-to-many relationship with Speaker
private Set speakers;
// Event has one-to-many relationship with Attendee
private Set attendees;
// ...
50

We enable you to leverage knowledge


anytime, anywhere!

One to Many : Using Set in Domain Class


Event has many speakers and attendees
Event event = new Event();
event.setName("Java Conference");
event.setSpeakers(new HashSet());
event.getSpeakers().add(new Speaker(biswa", jena"));
event.getSpeakers().add(new Speaker("Bill", "Clinton"));
session.saveOrUpdate(event);

51

We enable you to leverage knowledge


anytime, anywhere!

2. One to Many relationship: <list>


Group has many stories
<class name="Group" table="grouptable">
<id name="id" unsaved-value="0">
<generator class="increment" />
</id>
<list name="stories" cascade="all">
<key column="parent_id" />
<index column="idx" />
<one-to-many class="Story" />
</list>
<property name="name" type="string" />
</class>
52

We enable you to leverage knowledge


anytime, anywhere!

One to Many relationship :List


public class Group {
private int id;
private String name;
private List stories;
public void setStories(List l) {
stories = l;
}
public List getStories() {
return stories;
}
// ...
53

We enable you to leverage knowledge


anytime, anywhere!

One to Many relationship :Object


Instance
Group has many stories
// Create an Group object which has one to many
relationship with Story objects.
ArrayList list = new ArrayList();
list.add(new Story("Story Name 1"));
list.add(new Story("Story Name 2"));
list.add(new Story("Story Name 3"));
Group sp = new Group("My group 1");
sp.setStories(list);

54

We enable you to leverage knowledge


anytime, anywhere!

3. One to Many relationship: <array>


<class name="Group" table="grouptable">
<id name="id" unsaved-value="0">
<generator class="increment"/>
</id>
<array name="stories" cascade="all">
<key column="parent_id"/>
<index column="idx"/>
<one-to-many class="Story"/>
</array>
<property name="name" type="string"/>
</class>
55

We enable you to leverage knowledge


anytime, anywhere!

One to Many relationship :<array>


Group has many stories
public class Group {
private int id;
private String name;
// Group object has an array of Story objects
private Story[ ] stories;
public void setStories(Story[ ] l) {
stories = l;
}
public Story[] getStories() {
return stories;
}
56

We enable you to leverage knowledge


anytime, anywhere!

4. One to Many relationship: <bag>


Group has many stories
<class name="Group" table="grouptable">
<id name="id" unsaved-value="0">
<generator class="increment"/>
</id>
<bag name="stories" cascade="all">
<key column="parent_id"/>
<one-to-many class="Story"/>
</bag>
<property name="name" type="string"/>
</class>
57

We enable you to leverage knowledge


anytime, anywhere!

Many to Many relationship


Event has many speakers and speakers speak in many
events
<class name="SpeakerManyToMany table="m_speakers">
<id name="id" column="uid" type="long">
<generator class="increment"/> </id>
<property name="firstName" type="string" length="20"/>
<property name="lastName" type="string" length="20"/>
<set name="events" table="event_speakers
cascade="all">
<key column="speaker_id"/>
<many-to-many class="EventManyToMany"/>
</set></class>
58

We enable you to leverage knowledge


anytime, anywhere!

Many to Many relationship:


Event has many speakers
public class EventManyToMany {
private Long id;
private String name;
private Date startDate;
private int duration;
private Set speakers;
private Set attendees;
public void setSpeakers(Set speakers) {
this.speakers = speakers;
}
public Set getSpeakers() {
return speakers;
}
// ...
59

We enable you to leverage knowledge


anytime, anywhere!

Many to Many relationship:


A

speaker speaks in many events


public class SpeakerManyToMany {
private Long id;
private String firstName;
private String lastName;
private Set events;
public Set getEvents() {
return this.events;
}
public void setEvents(Set events) {
this.events = events;
}

60

We enable you to leverage knowledge


anytime, anywhere!

Mapping Object Inheritance

61

We enable you to leverage knowledge


anytime, anywhere!

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

We enable you to leverage knowledge


anytime, anywhere!

One Table per Concrete Class


Each concrete class mapped to normal persistent class
Pros
Easiest to implement
Cons
Data belonging to parent class is scattered across a
number of tables
A query in terms of parent class can cause large
number of select operation
Not recommended for most cases

63

We enable you to leverage knowledge


anytime, anywhere!

One Table per Subclass


One table for each class in the hierarchy
Foreign key relationship exists between common table
and subclass table
Advantage
Doesnt require complex changes to schema when a
single parent class is modified
Disadvantage
Poor performance as hierarchy grows , number of
joins required to construct a leaf class also grows
<joined- subclass> along with extends can be used in
mapping file

64

We enable you to leverage knowledge


anytime, anywhere!

One table per class hierarchy


A single table for the class hierarchy
Discriminator column contains key to identify the base type
Pros
Offers best performance since single select may suffice
Cons
Changes to members of the hierarchy require column to
be altered , added or removed from the table
Use <subclass> element with extends and discriminatorvalue attributes

65

We enable you to leverage knowledge


anytime, anywhere!

Annotations in Hibernate

66

We enable you to leverage knowledge


anytime, anywhere!

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!

Primary Key Generation

AUTO Hibernate decides the key generation strategy


IDENTITY- Database decides key genration
SEQUENCE -@SequenceGenerator
TABLE - @TableGenerator separate table for keys
Default strategy

@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!

Criteria Query API

69

We enable you to leverage knowledge


anytime, anywhere!

Criteria Query API


Provides a set of Java objects for constructing queries
Lets you build nested, structured query expressions in
Java programming language
Compile time syntax checking possible
Polymorphic behavior
Supports Query By Example (QBE)
Performing a query by providing an example object
that contain properties that need to be retrieved
Supports aggregation methods (from Hibernate 3)

70

We enable you to leverage knowledge


anytime, anywhere!

Creating Criteria object


Create org.hibernate.Criteria object via createCriteria()
factory method of the Session
Pass persistent object's class or its entity name to the
createCriteria() method
Call list() method of the Criteria object
// Get all instances of Person class and its subclasses
Criteria crit = sess.createCriteria(Person.class);
List results = crit.list();

71

We enable you to leverage knowledge


anytime, anywhere!

Pagination through ResultSet


Hibernate handles the pagination
Retrieving fixed number of objects
Two methods of Criteria class
setFirstResult() - set the first row in the result
setMaxResults() - number of rows to retrieve
Criteria crit = sess.createCriteria(Person.class);
crit.setFirstResult(2);
crit.setMaxResults(50);
List results = crit.list();

72

We enable you to leverage knowledge


anytime, anywhere!

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

We enable you to leverage knowledge


anytime, anywhere!

Methods of Restriction Class

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

We enable you to leverage knowledge


anytime, anywhere!

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

We enable you to leverage knowledge


anytime, anywhere!

Logical Grouping - Restrictions


Restrictions can be logically grouped
// Retrieve Person objects whose name has a pattern
// and whose age is 10 or null
List people = sess.createCriteria(Person.class)
.add( Restrictions.like("name", Biswa%") )
.add( Restrictions.or(
Restrictions.eq( "age", new Integer(10) ),
Restrictions.isNull("age)) )
.list();

76

We enable you to leverage knowledge


anytime, anywhere!

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

We enable you to leverage knowledge


anytime, anywhere!

Hibernate Query Language (HQL)

78

We enable you to leverage knowledge


anytime, anywhere!

Hibernate Query Capabilities (in 3.0)


Newly enhanced Hibernate Criteria Query API
Hibernate Query Language (HQL)
Enhanced support for queries expressed in the native
SQL dialect of the database

79

We enable you to leverage knowledge


anytime, anywhere!

Hibernate Query Language (HQL)


Very similar to SQL but less verbose
Understands OO inheritance, polymorphism ,
association, aggregation, composition
Selection: from, as
Associations and joins: inner join, outer join, right
outer join, full join
Projection: select, elements
Constraints: where
Other constructs: aggregate functions, expressions,
order by clauses, group by clauses, polymorphic
selections, sub-queries

80

We enable you to leverage knowledge


anytime, anywhere!

Differences from SQL

HQL is fully object-oriented, understanding notions like


inheritance, polymorphism and association
Queries are case-insensitive, except for names of Java
classes and properties

81

We enable you to leverage knowledge


anytime, anywhere!

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

Most of the time, you will need to assign an alias, since


you will want to refer to the Cat in other parts of the query
from Cat as cat (cat is the alias)
from Cat cat (as can be omitted)

82

We enable you to leverage knowledge


anytime, anywhere!

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

We enable you to leverage knowledge


anytime, anywhere!

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

We enable you to leverage knowledge


anytime, anywhere!

join types supported

inner join
left outer join
right outer join
full join (not usually useful)

85

We enable you to leverage knowledge


anytime, anywhere!

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

We enable you to leverage knowledge


anytime, anywhere!

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

We enable you to leverage knowledge


anytime, anywhere!

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

We enable you to leverage knowledge


anytime, anywhere!

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

We enable you to leverage knowledge


anytime, anywhere!

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

We enable you to leverage knowledge


anytime, anywhere!

Thank You

91

We enable you to leverage knowledge


anytime, anywhere!