You are on page 1of 134

Hibernate 3.

5
Prepared By Mumbai Academics

https://www.facebook.com/mumbai.academics.grou

Hibernate 3.5
Lesson 01: ntroduction to !"M and its #eed

Lesson !b%ecti&es
n this 'esson( you wi'' 'earn about:
!b%ect/"e'ation Mapping !b%ect)re'ation mpedence Mismatch *ibernate $.+ Bui'ding a ,imp'e App'ication

.hat is !b%ect/"e'ation Mapping/


t means how we wi'' map the re'ationa' wor'd with the ob%ect wor'd.
n the re'ationa' wor'd( the data is in the form of a tab'e that contains rows and co'umn. n the ob%ect wor'd( the data is in the form of an ob%ect.

An !"M ,o'ution
t consists of:
An AP ( to perform 0"12 30reate( "ead( 1pdate( 2e'ete4 operations on ob%ects of persistent c'asses A 'anguage to specify 5ueries that refer to c'asses and properties of c'asses A faci'ity( to specify mapping metadata A techni5ue( for the !"M imp'ementation to interact with transactiona' ob%ects to perform dirty checking. La6y association( fetching( and other optimi6ation functions.

.hy !"M/
t 7shie'ds8 de&e'opers from 7messy8 ,9L :his &iew ho'ds that ob%ect oriented de&e'opers cannot be e;pected to understand ,9L or re'ationa' databases ,ome of the benefits of !"M and *ibernate are:
Producti&ity Maintainabi'ity Performance <endor independence

Persistence and "e'ationa' 2atabase


Persistence means that we wou'd 'ike our app'ication=s data to out'i&e the app'ications process. n >a&a terms( we wou'd 'ike the state of 3some of4 our ob%ects to 'i&e beyond the scope of the ><M so that the same state is a&ai'ab'e 'ater. *ibernate is concerned with data persistence as it app'ies to re'ationa' databases 3"2BM,4.? n the wor'd of ob%ect)oriented app'ications( there is often a discussion about using an ob%ect database 3!2BM,4 as opposed to a "2BM,.

!b%ect)"e'ation mpedence Mismatch


!b%ect)re'ationa' mpedence Mismatch= means that ob%ect mode's and re'ationa' mode's do not work &ery we'' together. "2BM,s represent data in a tabu'ar format( whereas ob%ect)oriented 'anguages( such as >a&a( represent it as an interconnected graph of ob%ects. Loading and storing graphs of ob%ects using a tabu'ar re'ationa' database e;poses us to mismatch prob'ems...
Aranu'arity nheritance 3subtypes4 dentity

Aranu'arity
,ometimes you wi'' ha&e an ob%ect mode'( which has more c'asses than the number of corresponding tab'es in the database 3:he ob%ect mode' is more granu'ar than the re'ationa' mode'4 and &ice &ersa.

,ubtypes 3inheritance4
nheritance is a natura' paradigm in ob%ect)oriented programming 'anguages. *owe&er( "2BM,s do not define anything simi'ar on the who'e.

10

dentity
An "2BM, defines e;act'y one notion of =sameness=: the primary key. >a&a( howe&er( defines both ob%ect identity 3aCCb4 and ob%ect e5ua'ity 3a.e5ua's3b44.

11

ntroduction to *ibernate $.+


*ibernate is an open source !"M imp'ementation t mediates the app'icationEs interaction with a re'ationa' database( 'ea&ing the de&e'oper free to concentrate on the business prob'em at hand. *ibernate is an non)intrusi&e so'ution.

1D

ntroduction to *ibernate $.+


*ibernate $.+ is an imp'ementation of the >a&a Persistence AP standard that rep'aced o'der >a&a persistence so'utions such as the entity beans from Fnterprise >a&a Beans D. *ibernate $.+ has introduced standard persistence mechanism >PA and nfispan as caching mechanism.
1$

*ibernate Geatures
#o bui'd time bytecode generation #o specia' database tab'es G'e;ib'e !/" mapping

*ibernate Geatures 3continued4


1ses get/set methods and empty parameter constructor ,upports fine)grained ob%ects La6y initia'i6ation Automatic primary key generation with mu'tip'e strategies

*ibernate Geatures 3continued4


,upport for transactions inc'uding optimistic 'ocking Bui't in connection poo'ing or use popu'ar connection poo's Bui't in caching 3*ibernate 2ua' Layer 0ache Architecture4 Abstracts the &ariations in dia'ects between databases. Gor e;amp'e:
Hproperty nameCIdia'ectIJorg.hibernate.dia'ect.*,9L2ia'ectH/propertyJ

9uery by criteria
Gor a comp'ete set of features see http://www.hibernate.org

.hy *ibernate/
mpedance mismatch
!b%ect)oriented &s. re'ationa'

>a&a de&e'opers are not database de&e'opers


"educe the need for de&e'opers to know and fu''y understand database design( ,9L( performance tuning ncrease portabi'ity across database &endors

ncrease performance by deferring to e;perts


Potentia' decrease in database ca''s More efficient ,9L statements *ibernate cache usage
1K

2isad&antages of *ibernate
*ibernate may be s'ower than >2B0 *ibernateEs connection poo' is not great( but it works with the other popu'ar connection poo's ,upport for *9L 3*ibernate 9uery Language4 synta; cannot be found outside of *ibernate

*ibernate 0omponents

!&er&iew of *ibernate AP in a 'ayered Architecture

Architecture 0'asses
,essionGactory 3org.hibernate.,essionGactory4
A threadsafe 3immutab'e4 cache of compi'ed mappings for a sing'e database. A factory for ,ession and a c'ient of 0onnectionPro&ider.

,ession 3org.hibernate.,ession4
A sing'e)threaded( short)'i&ed ob%ect representing a con&ersation between the app'ication and the persistent store. .raps a >2B0 connection. Gactory for :ransaction. *o'ds a mandatory 3first)'e&e'4 cache of persistent ob%ects( used when na&igating the ob%ect graph or 'ooking up ob%ects by identifier.

Architecture 0'asses
Persistent ob%ects and co''ections
,hort)'i&ed( sing'e threaded ob%ects containing persistent state and business function. :hese might be ordinary >a&aBeans/P!>!s( the on'y specia' thing about them is that they are current'y associated with 3e;act'y one4 ,ession. As soon as the ,ession is c'osed( they wi'' be detached and free to use in any app'ication 'ayer 3e.g. direct'y as data transfer ob%ects to and from presentation4.

:ransient and detached ob%ects and co''ections


nstances of persistent c'asses that are not current'y associated with a ,ession. :hey may ha&e been instantiated by the app'ication and not 3yet4 persisted or they may ha&e been instantiated by a c'osed ,ession.

0onfiguration
:hree modes of configuration
1sing properties fi'e Programmatic 2ec'arati&e using LML configuration fi'e

LML 0onfiguration Gi'e


<?xml version='1.0' encoding='utf-8'? <!"#$%&'( )ibernate-configuration '*+,-$ .-//Hibernate/Hibernate $onfiguration "%" 3.0//(0. .)tt12//)ibernate.sourceforge.net/)ibernateconfiguration-3.0.dtd. <)ibernate-configuration <session-factor3 <1ro1ert3 name=.connection.driver4class. org.)s5ldb.6dbc"river</1ro1ert3 777.. <ma11ing resource=.events/(vent.)bm.xml./ <ma11ing resource=.events/'erson.)bm.xml./ </session-factor3 </)ibernate-configuration

1se 0onfiguration to get ,essionGactory


.hen a'' mappings ha&e been parsed by the 0onfiguration( the app'ication must obtain a factory for ,ession instances. :his factory is intended to be shared by a'' app'ication threads:
,essionGactory sessions C cfg.bui'd,essionGactory34M

>2B0 0onnections
1sua''y( you want to ha&e the ,essionGactory to create and poo' >2B0 connections for you. f you take this approach( opening a ,ession is as simp'e as: ,ession session C sessions.open,ession34M
// open a new ,ession

As soon as you do something that re5uires access to the database( a >2B0 connection wi'' be obtained from the poo'

>2B0 0onnections
*ibernate wi'' obtain 3and poo'4 connections using %a&a.s5'.2ri&erManager( if you set the fo''owing properties:

>2B0 0onnections
Gor use inside an app'ication ser&er( you shou'd a'most a'ways configure *ibernate to obtain connections from an app'ication ser&er 2atasource registered in >#2 . Nou='' need to set at 'east one of the fo''owing properties:

1se LML 0onfiguration to Aet sessionGactory


!btain ,essionGactory as
,essionGactory sf C new 0onfiguration34.configure34.bui'd,essionGacto ry34M

Nou can pick a different LML configuration fi'e using


,essionGactory sf C new 0onfiguration34 .configure3Icatdb.cfg.;m'I4 .bui'd,essionGactory34M

Bui'ding a *ibernate App'ication


2efine the domain mode' ,etup your *ibernate configuration
hibernate.cfg.;m'

0reate the domain ob%ect mapping fi'es


HdomainOob%ectJ.hbm.;m'

Make *ibernate aware of the mapping fi'es


1pdate the hibernate.cfg.;m' with 'ist of mapping fi'es

$0

"e&iew P 9uestions
mp'ement a *ibernate1ti' c'ass.
1sua''y taken from the *ibernate documentation

.rite your code

$1

Account !b%ect/:ab'e

hibernate.cfg.;m'

hibernate.cfg.;m'

hibernate.cfg.;m'

0onfiguring *ibernate
:here are mu'tip'e ways to configure *ibernate and an app'ication can 'e&erage mu'tip'e methods at once *ibernate wi'' 'ook for and use configuration properties in the fo''owing order
hibernate.properties 3when Qnew 0onfiguration34E is ca''ed4 hibernate.cfg.;m' 3when Qconfigure34E is ca''ed on 0onfiguration4 Programatic configuration settings

!b%ect Mapping Gi'es

Account.hbm.;m' Mapping Gi'e

*ibernate 2 Aenerators
#ati&e: Le&erages under'ying database method for generating 23se5uence( identity( etcR4 ncrement: Automatica''y reads ma; &a'ue of identity co'umn and increments by 1

11 2: 1ni&ersa''y uni5ue identifier combining P S 2ate 31D@)bit4 Many moreR

,ome more 2 generetaors

dentify Mapping Gi'es in the hibernate.cfg.;m'

*ibernate1ti'
0on&enience c'ass to hand'e bui'ding and obtaining the *ibernate ,ession Gactory.
1se recommended by the *ibernate org

,ession Gactory is thread)safe


,ing'eton for the entire app'ication

1sed to bui'd *ibernate Q,essionsE


*ibernate ,essions are #!: thread safe !ne per thread of e;ecution

*ibernate1ti'

:esting the 0ode

2emo
,tarting*ibernate 2emo

Hibernate 3.5
Lesson D: :he Persistence Life 0yc'e

Lesson !b%ecti&es
After comp'eting this 'esson( you wi'' be ab'e to e;p'ain the fo''owing topics:
*ibernate !b%ect Life 0yc'e Persistent ,tate :ransient !b%ect "emo&ed ,tate 2etached ,tate
-K

*ibernate !b%ect Life 0yc'e

:ransient ,tate
A'' ob%ects start off in the transient state
Account account C new Account34M
account is a transient ob%ect

*ibernate is not aware of the ob%ect instance #ot re'ated to database row
#o &a'ue for account d

Aarbage co''ected when no 'onger referenced by any other ob%ects

-B

Persistent ,tate
*ibernate is aware of( and managing( the ob%ect t has a database 2 :his is the on'y state where ob%ects are sa&ed to the database !b%ects are made persistent through ca''s against the *ibernate session P session.sa&e3account4M P session.'ock3account4M P session.update3account4M P session.merge3account4M

Persistent ,tate 30ontdR4

"emo&ed ,tate
A pre&ious'y persistent ob%ect that is de'eted from the database.
session.de'ete3account4M

>a&a instance may sti'' e;ist( but it is ignored by *ibernate


Any changes made to the ob%ect are not sa&ed to the database Picked up for garbage co''ection once it fa''s out of scope
*ibernate does not nu'')out the in)memory ob%ect

"emo&ed ,tate 30ontdR4

+$

2etached ,tate
A persistent ob%ect that is sti'' referenced after c'osure of the acti&e session.
session.c'ose34 changes ob%ectEs state from persisted to detached

,ti'' represents a &a'id row in the database #o 'onger managed by *ibernate.


0hanges made to detached ob%ects are not sa&ed to the database whi'e ob%ect remains in the detached state

+-

2etached ,tate 30ontdR4

++

Persistence 0onte;t
Managed ob%ect en&ironment
#o AP or concrete ob%ect to reference( %ust conceptua' :hought of as containing:
Araph of managed persistent instances List of ,9L statements to send to the database

Fach *ibernate session is said to ha&e one Qpersistence conte;tE.

+T

Persistence 0onte;t 30ontdR4

+K

G'ushing the 0onte;t


:he process of synchroni6ing the memory state with the database( usua''y on'y at the end of a unit of work( is ca''ed?f'ushing ,ubmits the stored ,9L statements to the database !ccurs when:
:ransactions commit34 or ro''back34 is ca''ed session.f'ush34 is ca''ed e;p'icit'y Before a 5uery is e;ecuted
f stored statements wou'd affect the resu'ts of the 5uery

G'ushing Modes
G'ush modes
session.setG'ushMode34
G'ushMode.A1:!: 2efau't. 0a''ed as described abo&e G'ushMode.0!MM :: #ot f'ushed before 5ueries G'ushMode.MA#1AL: !n'y when e;p'icit f'ush34 is ca''ed

0"12 30reate( "ead( 1pdate( 2e'ete4


0reating a row in database through hibernate using sa&e34 method

0"12 30ontdR4
"eading data from the database using hibernate

0"12 ) "eading 2ata


1pdating the data

0"12 ) 1pdating the "ecord in 2atabase


Any persistent ob%ect returned by get34 or any other kind of 5uery is a'ready associated with the current ,ession and transaction conte;t. t can be modified( and its state wi'' be synchroni6ed with the database.

0"12 ) 2ifference Between 'oad34 S get34

0"12 ) 1pdating detached nstance

0"12 ) 1pdating detached nstance 30ontdR4


:he 'ock34 method a'so a''ows an app'ication to reassociate an ob%ect with a new session. *owe&er( the detached instance has to be unmodifiedU
//%ust reassociate: sess.'ock3frit6( LockMode.#!#F4M //do a &ersion check( then reassociate: sess.'ock3i6i( LockMode."FA24M //do a &ersion check( using ,FLF0: ... G!" 1P2A:F( then reassociate: sess.'ock3pk( LockMode.1PA"A2F4M

0"12 ) 2e'ete
n order to a''ow con&enient remo&a' of entities from the database( the ,ession interface pro&ides a de'ete34 method( as fo''ows:
pub'ic &oid de'ete3!b%ect ob%ect4 throws *ibernateF;ception

0"12 P 2e'ete 30ontdR4


,ession session C sessions.open,ession34M :ransaction t; C session.begin:ransaction34M session.de'ete3user4M t;.commit34M session.c'ose34M n this case( the ca'' to de'ete34 undertakes two actions: t associates the ob%ect with the session and then schedu'es the ob%ect for de'etion( e;ecuted on t;.commit34.

"efreshing Fntities
*ibernate pro&ides a mechanism to refresh persistent ob%ects from their database representation. 1se one of the refresh34 methods on the ,ession interface to refresh an instance of a persistent ob%ect( as fo''ows: pub'ic &oid refresh3!b%ect ob%ect4 throws *ibernateF;ception pub'ic &oid refresh3!b%ect ob%ect( LockMode 'ockMode4 throws *ibernateF;ception

2emo
2emo: *ibernate0"12

:ransactions
A transaction is a unit of work guaranteed to beha&e as if you ha&e e;c'usi&e use of the database. f you wrap your work in a transaction( the beha&ior of other system users wi'' not affect your data. A transaction can be started( committed to write data to the database( or ro''ed back to remo&e a'' changes from the beginning onward . :ransactions and 'ocking are intimate'y re'atedVthe 'ocking techni5ues chosen to enforce a transaction can determine both the performance and 'ike'ihood of success of the transaction.

:ransactions 30ontdR4
:o achie&e this( you obtain a :ransaction ob%ect from the database 3beginning the transaction4 and manipu'ate the session as shown in the fo''owing code:

Hibernate 3.5
Lesson 3: Hibernate Association and Collection Mapping

Lesson !b%ecti&es After comp'eting this 'esson( you wi'' be


ab'e to e;p'ain the fo''owing topics:
many)to)one one)to)one

1nidirectiona' Associations

Bi)directiona' Associations
one)to)many/many)to)one one)to)one

K-

Lesson !b%ecti&es 30ontdR4


0o''ection Mapping
Association 1sing ,F:

Associations
Association represents re'ationship between entities. :here is no directiona'ity in&o'&ed in re'ationa' wor'd( its %ust a matter of writing a 5uery. But there is notion of directiona'ity which is possib'e in %a&a. Gor hibernate association are of two types:
1nidirectiona' Bidirectiona'

1nidirectiona' Associations 3many) to)one4


Hc'ass nameCIPersonIJ Hid nameCIidI co'umnCIperson dIJ Hgenerator c'assCInati&eI/J H/idJ Hmany)to)one nameCIaddressI c'assC7Address8 co'umnCIaddress dI not)nu''CItrueI/ cascadeC7a''8J H/c'assJ Hc'ass nameCIAddressIJ Hid nameCIidI co'umnCIaddress dIJ Hgenerator c'assCInati&eI/J H/idJ H/c'assJ

!ne):o)!ne
Hc'ass nameCIPersonIJ Hid nameCIidI co'umnCIperson dIJ Hgenerator c'assCInati&eI/J H/idJ H/c'assJ Hc'ass nameCIAddressIJ Hid nameCIidI co'umnCIperson dIJ Hgenerator c'assCIforeignIJ Hparam nameCIpropertyIJpersonH/paramJ H/generatorJ H/idJ Hone)to)one nameCIpersonI constrainedCItrueI/J H/c'assJ

1sing many)to)one F'ement to 0reate one)to)one "e'ationship

<class?nameCIcom.patni.student.,tudentI? tab'eCI,:12F#:IJ

,tudent.hbm.;m'

<id?nameCIstudent dI?typeCI'ongI?co'umnCI,:12F#:O 2IJ <generator?c'assCInati&eI?/J</id <1ro1ert3?nameCIstudent#ameI?typeCIstringI?not) nu''CItrueI'engthCI100I?co'umnCI,:12F#:O#AMFI?/J <man3-to-one8 nameCIstudentAddressIc'assCIcom.patni.student.Address7 co'umnCI,:12F#:OA22"F,,Inot) nu''CItrueI?cascadeCIa''I?uni5ue=.true.?/J </class

<class?nameCIcom.patni.student.AddressI? tab'eCIA22"F,,IJ

Address.hbm.;m'

<id?nameCIaddress dI?typeCI'ongI?co'umnCIA22"F,,O 2IJ <generator?c'assCInati&eI?/J </id <1ro1ert3?nameCIstreetI?co'umnCIA22"F,,O,:"FF:I? typeCIstringI'engthCID+0I?/J <1ro1ert38nameCIcityI?co'umnCIA22"F,,O0 :NI? typeCIstringI'engthCI+0I?/J <1ro1ert3?nameCIstateI?co'umnCIA22"F,,O,:A:FI? typeCIstringI'engthCI+0I?/J <1ro1ert3?nameCI6ipcodeI?co'umnCIA22"F,,OW P0!2FI? typeCIstringI'engthCI10I?/J </class

,tudent c'ass
pub'ic?c'ass?,tudent?imp'ements?%a&a.io.,eria'i6ab'e X pri&ate?'ong?student dM pri&ate?,tring student#ameM pri&ate?Address studentAddressM? pub'ic?,tudent34 X Y . . .

Address c'ass
pub'ic?c'ass?Address?imp'ements?%a&a.io.,eria'i6ab'e X pri&ate?'ong?address dM pri&ate?,tring streetM pri&ate?,tring cityM pri&ate?,tring stateM pri&ate?,tring 6ipcodeM ?pub'ic?Address34 X Y

2emo
#ne4to4one #ne4to4man3

Bidirectiona' Associations one)to)many / many)to)one


Hc'ass nameCIPersonIJ Hid nameCIidI co'umnCIperson dIJ Hgenerator c'assCInati&eI/J H/idJ Hmany)to)one nameCIaddressI co'umnCIaddress d7 not)nu''CItrueI/J H/c'assJ Hc'ass nameCIAddressIJ Hid nameCIidI co'umnCIaddress dIJ Hgenerator c'assCInati&eI/J H/idJ Hset nameCIpeop'eI inverse=.true. Hkey co'umnCIaddress dI/J Hone)to)many c'assCIPersonI/J H/setJ H/c'assJ

Bidirectiona' Associations3fk4 one)to) one


A?bidirectiona' one)to)one association on a foreign key?is common: Hc'ass nameCIPersonIJ Hid nameCIidI co'umnCIperson dIJ Hgenerator c'assCInati&eI/J H/idJ Hmany)to)one nameCIaddressI co'umnCIaddress dI
uni5ueCItrueI not)nu''CItrueI/J

H/c'assJ Hc'ass nameCIAddressIJHid nameCIidI co'umnCIaddress dIJ


Hgenerator c'assCInati&eI/JH/idJ

Hone)to)one nameCIpersonI property)refCIaddressI/J H/c'assJ

Bidirectiona' Associations3pk4 one) to)one


A?bidirectiona' one)to)one association on a primary key? uses the specia' id generator: Hc'ass nameCIPersonIJ Hid nameCIidI co'umnCIperson dIJ Hgenerator c'assCInati&eI/J H/idJ Hone)to)one nameCIaddressI/J H/c'assJ Hc'ass nameCIAddressIJ Hid nameCIidI co'umnCIperson dIJ
Hgenerator c'assCIforeignIJ

Hparam nameCIpropertyIJpersonH/paramJ H/generatorJ H/idJ Hone)to)one nameCIpersonI


constrainedCItrueI/J

H/c'assJ

0o''ection Mapping
Association S 0o''ection mapping tags are practica''y identica'. *ibernate 0o''ection :ypes
HsetJ
1nordered/!rdered( re5uiring &a'ue co'umn

HmapJ
1nordered/!rdered( re5uiring key and &a'ue co'umns

0o''ection Mapping 30ontdR4


H'istJ
!rdered( re5uiring an inde; co'umn on the referenced ob%ect tab'e

HarrayJ
Map to >a&a :ype and Primiti&e Arrays !rdered( re5uiring an inde; co'umn on the referenced ob%ect tab'e

HbagJ
#o direct imp'ementation a&ai'ab'e in >a&a 1nordered/ordered co''ection a''owing dup'icates

0o''ection Mapping 30ontdR4


"ea'i6ed through 0o''ection/List "e5uires &a'ue co'umn

HidbagJ
1sed for many)to)many re'ationships ,ame as Bag( but with additiona' identifier co'umn used for surrogate keys "e5uires an 2 Aenerator %ust 'ike Fntity c'asses

Association as HsetJ
9a1s to a :;et< interface
mp's inc'ude *ash,et( :ree,et( etcR

$an be o1tionall3 sorted


FBi''er has many FBi''s 31:M / M:14

(+ill 9a11ing Hmany)to)one nameCIebi''erI co'umnCIFB LLF"O 2I c'assCIcourses.hibernate.&o.FBi''erI /J (+iller 9a11ing Hset nameCIebi''sI in&erseCItrueI sortCIunsortedZnatura'Zmy.custom.My0omparatorIJ Hkey co'umnCIFB LLF"O 2I not)nu''CItrueI/J Hone)to)many c'assCIcourses.hibernate.&o.FBi''I/J H/setJ

2emo
!neOtoOone !neOtoOmany hibernate!ne:oManybidirectiona' !ne:oManyBi2irectiona'.ith,et

Hibernate 3.5
Lesson 0-: :ransaction Management

Lesson !b%ecti&es
n this 'esson( you wi'' 'earn:
Programmatic :ransaction Management 2ec'arati&e :ransaction Management 1sing 2ata ,ource for :ransaction Management

:ransaction
"epresents a sing'e unit)of)work A'' or nothing P either a'' of the actions get committed or the entire effort fai's. F;amp'e:
:ransfer Money Between Accounts ,tep 1: .ithdraw [+00 from ,a&ings Account ,tep D: 2eposit [+00 into 0hecking Account

.hat happens if the system crashes after ,tep 1( but before ,tep D/

:ransaction 3continued4
*ibernate communicates with the database &ia a >2B0 0onnectionM hence it must support both AP s. n a stand)a'one 3or web)based4 app'ication( on'y the >2B0 transaction hand'ing is a&ai'ab'eM in an app'ication ser&er( *ibernate can use >:A. ,ince we wou'd 'ike *ibernate app'ication code to 'ook the same in both managed and non)managed en&ironments( *ibernate pro&ides its own abstraction 'ayer( hiding the under'ying transaction AP .

:ransaction
*ibernate needs a way to abstract the &arious transaction strategies from the en&ironment. *ibernate has its own :ransaction c'ass that is accessib'e from the ,ession interface( demonstrated here:

n this e;amp'e( factory is an initia'i6ed ,essionGactory instance. :his code creates an instance of the org.hibernate.:ransaction c'ass and then commits the :ransaction instance.#otice that you don=t need to ca'' session.f'ush34. 0ommitting a transaction automatica''y f'ushes the ,ession ob%ect. :he F&ent instance is persisted to the database when the transaction is committed. :he transaction strategy you use 3>2B0 or >:A4 doesn=t matter to the app'ication code)it=s set in the *ibernate configuration fi'e.

:he transaction.factoryOc'ass property defines the transaction strategy that *ibernate uses. :he defau't setting is to use >2B0 transactions since they=re the most common. :o use >:A transactions( you need to set the fo''owing properties in hibernate.cfg.;m':

:ransaction

:he transaction.factoryOc'ass property te''s *ibernate that you='' be using >:A transactions. 0urrent'y( the on'y other option to >:A is >B20 transactions( which is the defau't. >:A transactions are retrie&ed from a >#2 1" ( which is specified using the %ta.1ser):ransaction property. f you don=t know the 1" for your specific app'ication ser&er( the defau't &a'ue is %a&a:comp/1ser:ransaction.

Programmatic :ransactions in *ibernate


org.hibernate.:ransaction
begin34M commit34M ro''back34M set:imeout34M !btained through session
session.begin:ransaction34M session.get:ransaction34M

.orks in a non)managed p'ain >2B0 en&ironment and a'so with app'ication ser&ers using >:A

Programmatic :ransactions in *ibernate


%a&a;.transaction.1ser:ransaction
>a&a :ransaction AP 3>:A4 &ersion *ibernate recommends this as the primary choice whene&er itEs a&ai'ab'e

Programmatic :ransactions in #ati&e *ibernate


try X ,ession session C *ibernate1ti'.get,essionGactory34.get0urrent,ession34M // session obtains connection and sets auto0ommit3fa'se4 session.begin:ransaction34M // ... // modify and ca'' persistent methods on &arious ob%ects // ... // f'ush the Persistence 0onte;t and commit to the database session.get:ransaction34.commit34M catch 3*ibernateF;ception he4 X // ro'' back if an e;ception occurs session.get:ransaction34.ro''back34M Y fina''y X // c'ose session and return connection to poo' session.c'ose34M Y

Programmatic :ransactions in *ibernate with >:A


*ibernate recommends 'e&eraging >:A o&er nati&e *ibernate AP s when a&ai'ab'e .ithin a >:A en&ironment( actions are tied to the >:A system transaction #eed to te'' *ibernate about >:A( and the &endor specific :ransactionManager

Programmatic :ransactions in *ibernate with >:A

Programmatic :ransactions in *ibernate with >:A


Hsession)factoryJ ... Hproperty nameCIcurrentOsessionOconte;tOc'assIJ %ta H/propertyJ HpropertynameCItransaction.factoryOc'assIJ org.hibernate.transaction.>:A:ransactionGactory H/propertyJ Hproperty nameCItransaction.managerO'ookupOc'assIJ HU)) se'ected on a per)&endor basis ))J org.hibernate.transaction.>Boss:ransactionManagerLookup H/propertyJ ... H/session)factoryJ

2ec'arati&e :ransactions
Pushes transaction management and responsibi'ity to the app ser&er.
0ontainer)managed)transactions

2oesnEt re5uire e;tra boi'erp'ate code


Much c'eaner and easier to read Fasier to fo''ow the business 'ogic

#o need to manua''y start and stop transactionsU

2ec'arati&e :ransactions
HU)) 2ec'arati&e :ransaction Management ))J Hproperty nameCIcurrentOsessionOconte;tOc'assIJ%taH/propertyJ Hproperty nameCItransaction.factoryOc'assIJ org.hibernate.transaction.0M::ransactionGactoryH/propertyJ Hproperty nameCItransaction.managerO'ookupOc'assIJ org.hibernate.transaction.>Boss:ransactionManagerLookup H/propertyJ

>Boss 2atasource P 'ectureT2,.;m'

H/;m' &ersionCI1.0I encodingCI1:G)@I/J HdatasourcesJ H'oca')t;)datasourceJ H%ndi)nameJLectureT2,H/%ndi)nameJ HU)) !rac'e 0onfiguration ))J Hconnection)ur'J %dbc:orac'e:thin:\'oca'host:1+D1:LFH/connection)ur'J Hdri&er)c'assJ orac'e.%dbc.dri&er.!rac'e2ri&er H/dri&er)c'assJ Huser)nameJ'ectureTH/user)nameJ HpasswordJ'ectureTH/passwordJ Hmin)poo')si6eJ+H/min)poo')si6eJ Hma;)poo')si6eJ100H/ma;)poo')si6eJ H/'oca')t;)datasourceJ H/datasourcesJ

*erbernateOwithO2atasource

2emo

*ibernate $.+
Lesson 0+: ,earches and 9ueries

Lesson !b%ecti&es
n this 'esson( you wi'' 'earn:
*ibernate 9uery Language3*9L4 *ibernate Pro%ections

110

*ibernate 9uery Language3*9L4


*9L is a 'anguage for ta'king about 7sets of ob%ects8 t unifies re'ationa' operations with ob%ect mode's *9L is an ob%ect)oriented 5uery 'anguage( simi'ar to ,9L( but instead of operating on tab'es and co'umns( *9L works with persistent ob%ects and their properties. *9L is a 'anguage with its own synta; and grammar.

*ibernate 9uery Language


*ibernate 9uery Language is used to e;ecute 5ueries against database. *ibernate automatica''y generates the s5' 5uery and e;ecute it against under'ying database if *9L is used in the app'ication. *9L is based on the re'ationa' ob%ect mode's and makes the ,9L ob%ect oriented. *ibernate 9uery Language uses 0'asses and properties instead of tab'es and co'umns. *ibernate 9uery Language is e;treme'y powerfu' and it supports Po'ymorphism( Associations( Much 'ess &erbose than ,9L

*ibernate 9uery Language


Make ,9L be ob%ect oriented
0'asses and properties instead of tab'es and co'umns Po'ymorphism Associations Much 'ess &erbose than ,9L

Gu'' support for re'ationa' operations


nner/outer/fu'' %oins( cartesian products Pro%ection Aggregation 3ma;( a&g4 and grouping !rdering ,ub5ueries ,9L function ca''s

.hy to use *9L/


Gu'' support for re'ationa' operations??? "eturn resu't as !b%ect??? Po'ymorphic 9ueries
Po'ymorphic 5ueries resu'ts the 5uery resu'ts a'ong with a'' the chi'd ob%ects if any???

Fasy to Learn??? ,upport for Ad&ance features


*9L contains many ad&ance features such as pagination( fetch %oin with dynamic profi'ing( nner/outer/fu'' %oins( 0artesian products. t a'so supports Pro%ection( Aggregation 3ma;( a&g4 and grouping

2atabase independent

:he from 0'ause and A'iases


,imp'e shortcut 5uery to se'ect a'' ob%ects from the Product tab'e 7from Product as p or from Product as product8 :he from c'ause is &ery basic and usefu' for working direct'y with ob%ects. ,tring?,9LO91F"N?CIfrom? nsurance?insuranceIM ?9uery?5uery?C?session.create9uery3,9LO91F"N4M ?for3 terator?itC5uery.iterate34Mit.has#e;t34M4X nsurance?insuranceC3 nsurance4it.ne;t34M ?,ystem.out.print'n3I 2:?I?]insurance.getLng nsurance d344M ?,ystem.out.print'n3IGirst ?#ame:?I?]?insurance.get nsurance#ame344M ?Y??session.c'ose34M ?

*9L se'ect 0'ause


:he se'ect c'ause pro&ides more contro' o&er the resu't set than the from c'ause. f you want to obtain the properties of ob%ects in the resu't set( use the se'ect c'ause

//0reate?,e'ect?0'ause?*9L ?,tring?,9LO91F"N?CI,e'ect?insurance.'ng nsurance d( insurance.insurance#ame(I?]?Iinsurance.in&estementAmount(

insurance.in&estement2ate?from? nsurance?insuranceIM ?9uery?5uery?C?session.create9uery3,9LO91F"N4M ?for3 terator?itC5uery.iterate34Mit.has#e;t34M4X ?!b%ect^_?row?C?3!b%ect^_4?it.ne;t34M ?,ystem.out.print'n3I 2:?I?]?row^0_4M ?,ystem.out.print'n3I#ame:?I?]?row^1_4M ?,ystem.out.print'n3IAmount:?I?]?row^D_4M ?Ysession.c'ose34M ?

*9L se'ect 0'ause


.here 0'ause is used to 'imit the resu'ts returned from database. t can be used with a'iases and if the a'iases are not present in the 9uery( the properties can be referred by name. ,tring?,9LO91F"N?CI?from? nsurance ?as?insurance?where?insurance.'ng nsurance dC=1=IM ?9uery?5uery?C?session.create9uery3,9LO91F"N4M ?for3 terator?itC5uery.iterate34 Mit.has#e;t34M4 X ? nsurance?insuranceC3 nsurance4it.ne;t34M ?,ystem.out.print'n3I 2:?I?]?insurance.getLng nsurance d344M ?,ystem.out.print'n3I#ame:?I? ]insurance.get nsurance#ame344M ?Y

:he where c'ause

:he?where?c'ause a''ows you to refine the 'ist of instances returned. f no a'ias e;ists( you can refer to properties by name:
from 0at where nameC=Grit6= from 0at as cat where cat.nameC=Grit6=
:his returns instances of?0at?named =Grit6=.

se'ect foo from Goo foo( Bar bar where foo.start2ate C bar.date
returns a'' instances of?Goo?with an instance of?bar?with a?date?property e5ua' to the?start2ate?property of the?Goo

:he order by c'ause

:he 'ist returned by a 5uery can be ordered by any property of a returned c'ass or components: 7from 2omestic0at cat order by cat.name asc( cat.weight desc( cat.birthdate8 :he optiona'?asc?or?desc?indicate ascending or descending order respecti&e'y.

:he group by c'ause

A 5uery that returns aggregate &a'ues can be grouped by any property of a returned c'ass or components:
se'ect cat.co'or( sum3cat.weight4( count3cat4 from 0at cat group by cat.co'or .

A?ha&ing?c'ause is a'so a''owed.


se'ect cat.co'or( sum3cat.weight4( count3cat4 from 0at cat group by cat.co'or ha&ing cat.co'or in 3eg.0o'or.:ABBN( eg.0o'or.BLA0`4

*9L aggregate functions


*ibernate supports mu'tip'e aggregate functions. when they are used in *9L 5ueries( they return an aggregate &a'ue 3such as sum( a&erage( and count4 ca'cu'ated from property &a'ues of a'' ob%ects satisfying other 5uery criteria. :hese functions can be used a'ong with the distinct and a'' options( to return aggregate &a'ues ca'cu'ated from on'y distinct &a'ues and a'' &a'ues 3e;cept nu'' &a'ues4( respecti&e'y.

*9L aggregate functions


Go''owing is a 'ist of aggregate functions with their respecti&e synta;M a'' of them are se'f) e;p'anatory. count3 ^ distinct Z a'' _ ob%ect Z ob%ect.property 4 count3a4?3e5ui&a'ent to count3a'' ...4( counts nu'' &a'ues a'so4 sum 3 ^ distinct Z a'' _ ob%ect.property4 a&g3 ^ distinct Z a'' _ ob%ect.property4 ma;3 ^ distinct Z a'' _ ob%ect.property4 min3 ^ distinct Z a'' _ ob%ect.property4

*9L aggregate functions


F;amp'e: 7se'ect cat.weight ] sum3kitten.weight4 from 0at cat %oin cat.kittens kitten group by cat.id( cat.weight 7 se'ect distinct cat.name from 0at cat se'ect count3distinct product.supp'ier.name4 from Product product

1sing "estrictions with *9L


As with ,9L( you use the where c'ause to se'ect resu'ts that match your 5ueryEs e;pressions. *9L pro&ides many different e;pressions that you can use to construct a 5uery. n the *9L 'anguage grammar( there are the fo''owing possib'e e;pressions:
Logic operators: !"( A#2( #!: F5ua'ity operators: C( HJ( UC( bC 0omparison operators: H( J( HC( JC( 'ike( not 'ike( between( not between

1sing "estrictions with *9L


Math operators: ]( )( a( / 0oncatenation operator: ZZ 0ases: 0ase when H'ogica' e;pressionJ then Hunary e;pressionJ e'se OHunarye;pressionJ end 0o''ection e;pressions: some( e;ists( a''( any

F;amp'e:
from Product where price J D+.0 and name 'ike =MoucQ from 2omestic0at cat where cat.name between =A= and =B= from 2omestic0at cat where cat.name in 3 =Goo=( =Bar=( =Ba6= 4

1sing #amed Parameters


*ibernate supports named parameters in its *9L 5ueries. :his makes writing 5ueries that accept input from the user easyVand you do not ha&e to defend against ,9L in%ection attacks. ,9L in%ection is an attack against app'ications that create ,9L direct'y from user input with string concatenation. Gor instance( if we accept a name from the user through a web app'ication form( then it wou'd be &ery bad form to construct an ,9L 3or *9L4 5uery 'ike this:
,tring s5' C Ise'ect p from products where name C =I ] name ] I=IM

1sing #amed Parameters


*ibernateEs named parameters are simi'ar to the >2B0 5uery parameters 3/4 you may a'ready be fami'iar with( but *ibernateEs parameters are 'ess confusing. t is a'so more straightforward to use *ibernateEs named parameters if you ha&e a 5uery that uses the same parameter in mu'tip'e p'aces :he simp'est e;amp'e of named parameters uses regu'ar ,9L types for the parameters: ,tring h5' C Ifrom Product where price J :priceIM 9uery 5uery C session.create9uery3h5'4M 5uery.set2oub'e3IpriceI(D+.04M List resu'ts C 5uery.'ist34M

1sing #amed Parameters


.hen the &a'ue to be pro&ided wi'' be known on'y at run time( you can use some of *9LEs ob%ect)oriented features to pro&ide ob%ects as &a'ues for named parameters. :he 9uery interface has a setFntity34 method that takes the name of a parameter and an ob%ect. ,tring supp'ier*9L C Ifrom ,upp'ier where nameC=Mega nc=IM 9uery supp'ier9uery C session.create9uery3supp'ier*9L4M ,upp'ier supp'ier C 3,upp'ier4 supp'ier9uery.'ist34.get304M ,tring h5' C Ifrom Product as product where product.supp'ierC:supp'ierIM 9uery 5uery C session.create9uery3h5'4M 5uery.setFntity3Isupp'ierI(supp'ier4M List resu'ts C 5uery.'ist34

#amed *9L 9uery in Mapping Gi'e

Aet #amed *9L 9uery from Mapping Gi'e


,ession?session?C?*ibernate1ti'.current,ession34M ????9uery?5uery?C?session.get#amed9uery3I*9LpricingI4M ????????List?resu'ts?C?5uery.'ist34M ????????disp'ay!b%ectList3resu'ts4M static?pub'ic?&oid?disp'ay!b%ectList3List?'ist4

????X ???????? terator?iter?C?'ist.iterator34M ????????if?3Uiter.has#e;t344 ????????X ????????????,ystem.out.print'n3I#o?ob%ects?to?disp'ay.I4M ????????????returnM ????????Y ????????whi'e?3iter.has#e;t344 ????????X ????????????,ystem.out.print'n3I#ew?ob%ectI4M ????????????!b%ect?ob%?C?3!b%ect4?iter.ne;t34M ????????????,ystem.out.print'n3ob%4M?YY???????

!btaining a 1ni5ue "esu't


*9LEs 9uery interface pro&ides a uni5ue"esu't34 method for obtaining %ust one ob%ect from an *9L 5uery.

9uery 5uery C session.create9uery3h5'4M 5uery.setMa;"esu'ts314M Product product C 3Product4 5uery.uni5ue"esu't34M //test for nu'' here if needed

,orting "esu'ts with the order by 0'ause


:o sort your *9L 5ueryEs resu'ts( you wi'' need to use the order by c'ause. Nou can order the resu'ts by any property on the ob%ects in the resu't set: either ascending 3asc4 or descending 3desc4. Nou can use ordering on more than one property in the 5uery if you need to. A typica' *9L 5uery for sorting resu'ts 'ooks 'ike this: from Product p where p.priceJD+.0 order by p.price desc f you wanted to sort by more than one property( you wou'd %ust add the additiona' properties to the end of the order by c'ause( separated by commas. Gor instance( you cou'd sort by product price and the supp'ierEs name( as fo''ows: from Product p order by p.supp'ier.name asc( p.price asc

1sing Mu'tip'e :ab'e


Associations a''ow you to use more than one c'ass in an *9L 5uery( %ust as ,9L a''ows you to use %oins between tab'es in a re'ationa' database. Add an association to an *9L 5uery with the %oin c'ause. *ibernate supports fi&e different types of %oins: inner %oin( cross %oin( 'eft outer %oin( right outer %oin( and fu'' outer %oin. f you use cross %oin( %ust specify both c'asses in the from c'ause 3from Product p( ,upp'ier s4. Gor the other %oins( use a %oin c'ause after the from c'ause. ,pecify the type of %oin( the ob%ect property to %oin on( and an a'ias for the other c'ass.

1sing Mu'tip'e :ab'e


F;amp'e1: 7se'ect s.name( p.name( p.price from Product p inner %oin p.supp'ier as s8 F;amp'eD: 7from 0at as cat inner %oin cat.mate as mate 'eft outer %oin cat.kittens as kitten 7 Nou may supp'y e;tra %oin conditions using the *9L with keyword. F;amp'e $: 7from 0at as cat 'eft %oin cat.kittens as kitten with kitten.body.eight J 10.0 7

You might also like