Professional Documents
Culture Documents
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
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
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
1D
*ibernate Geatures
#o bui'd time bytecode generation #o specia' database tab'es G'e;ib'e !/" mapping
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'
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
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.
0onfiguration
:hree modes of configuration
1sing properties fi'e Programmatic 2ec'arati&e using LML configuration fi'e
>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:
$0
"e&iew P 9uestions
mp'ement a *ibernate1ti' c'ass.
1sua''y taken from the *ibernate documentation
$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
*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
*ibernate1ti'
0on&enience c'ass to hand'e bui'ding and obtaining the *ibernate ,ession Gactory.
1se recommended by the *ibernate org
*ibernate1ti'
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
: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
-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
"emo&ed ,tate
A pre&ious'y persistent ob%ect that is de'eted from the database.
session.de'ete3account4M
+$
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
+-
++
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
+T
+K
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 30ontdR4
"eading data from the database using hibernate
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
"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
1nidirectiona' Associations
Bi)directiona' Associations
one)to)many/many)to)one one)to)one
K-
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'
!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
<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
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
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
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
(+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.
.orks in a non)managed p'ain >2B0 en&ironment and a'so with app'ication ser&ers using >:A
2ec'arati&e :ransactions
Pushes transaction management and responsibi'ity to the app ser&er.
0ontainer)managed)transactions
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
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
2atabase independent
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 ?
: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 '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.
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 .
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
????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???????
9uery 5uery C session.create9uery3h5'4M 5uery.setMa;"esu'ts314M Product product C 3Product4 5uery.uni5ue"esu't34M //test for nu'' here if needed