Hibernate (An ORM Tool)
Hibernate (An ORM Tool)
Hibernate
(By Sumanth Sir, InetSolv- Hyderabad )
Please like document on Scribd.
Coyri!ht document
2
Hibernate is a "rame #ork. Hibernate "rame #ork is used to develo a
$ava alication to interact #ith database server.
% "rame #ork is a iece o" so"t#are this iece o" so"t#are contains
solutions "rom commonly reeatedly occurred roblems accurs multile
ro$ects.
IDE (Integrate Development Environment)&
%s art o" I'( all the comonents are inte!rated.
Ex& (ditors, Comileras, Servers, Bro#ser etc.
By usin! I'( #e can develo ro$ect )uickly.
I'( is #ill imrove the roductivity o" the develoer.
*he "ollo#in! are the most oular I'(,s.
+. (clise
2. ,y (clise
-. .et Beans
/. 0%' (0elational %lication 'eveloment)
1. 2 Builder
*o #ork #ith I'( #e re)uired a 3#orksace4 "older.
% #ork sace "older contains all the 5les #hich are related to that
ro$ect.
6hen #e double click on (clise.e7e it #ill launch a dialo! #hose name
is #ork sace launch. *o this #ork sace launch #e have to suly #ork
sace "older as inut.
6hen #e start the (clise I'( in the #ork sace "older it has created a
"older #ith the name.matadata. *his "older contains all the 5les #hich
are used by (clise I'(.
(clise I'( contains set o" ersective by de"ault (clise I'( launch8s 2((
ersective.
% ersective contains set o" vie#s. % vie# is a (mail #indo#. %
ersective contains set o" vie#s.
I" #e #ould like to er"orm any oerations in I'( #e must create a
ro$ect.
Procedure to create the project in IDE&
Ste +& 5le ne# ro$ect.
2
Ste 2& select the aroriate ro$ect and click on ne7t button.
Ste -& in ne# $ava ro$ect #indo# enter the ro$ect name and click on
5nish.
Ste /& #e delete the ro$ect #ith out checkin! the check bo7. *he 5les
#ill not delete ermanently.
%s art o" $ava rosective #e use out line vie# to see all the variables
and methods #hich are available in class.
*he acka!e e7lorer vie# is used to see all the 5les #hich are available
in the ro$ect.
Select Pro$ect Proerties $ava Build ath library add
e7ternal $ar 5les.
In I'( #e can disable auto build rocess (Pro$ect builds
automatically).
Note&
6e can chan!e the short cuts o" (clise I'(
(6indo# Pre"erences 9eneral :eys).
%s art o" a (clise I'( #e can relace or !et the old code by usin!
comare #ith or relace #ith local history.
*o create a $ar 5les #e use an otion e7ort (5les e7ort).
;Procedure to create web based application&
Ste +& 5le ne# #eb ro$ect.
Ste 2& *he above ste #ill dislay a dialo! #ith the name <ne# #eb
ro$ect8. In that dialo! enter the ro$ect name make sure that ro$ect
name and #eb root "older name is same.
6hen #e #ork #ith I'( to con5!ure in deloyment descritor #e have
t#o otions. *hey are like source and desi!n. *o see the contents o"
#eb.7ml 5le #e can use an otion source.
By usin! !rahical user inter"ace i" #e #ant con5!ure servlets. 6e can
use desi!n vie#.
6hen #e use I'( #e no need to deloy the ro$ect manually. 6e can
con5!ure I'( to deloy the ro$ect. %s art o" 2(( resective. #e can use
server vie# to con5!ure the ro$ect in I'(.
Ctrl =
2
Ste +& 9et the server vie# and ri!ht click chooses an otion con5!ure
server connector.
Ste 2& Choose the aroriate server the home directory o" the server.
Same servers
re)uired user name and ass#ord suly these values and click
on 3>:4.
Ste -& *o add the ro$ect to server #e can use an otion add
deloyment.
Ste /& *hey are some I'(8s are available #hich are resonsible to
interact #ith database
Servers. *he oular I'(8s "or oracle database server are *>%'
and S?@ develoer.
Aor the database server like ,BS?@ #e can use 3,BS?@
#orkbench4.
Ste 1& In the comanies because o" licenses issues #e may not use the
I'( like *>%'.
(clise !ives has rovided a "eature to interact #ith database
servers. 6e can use
(cliseC,B(C@IPS( to interact #ith database servers.
;Procedures to confgure IDE to interact with database server&
+. >en ,B(C@IPS( database e7lorer o" rosective.
2. In the database bro#ser vie# #hen #e ri!ht click it lunches a ou
menu "rom that choose an otion ne#.
-. *he above ste as lunched a #indo# #hose name is database
driver "rom that choose driver temlate and rovide a driver name.
.o# #e have to suly driver class, url, username, ass#ord to
interact #ith 'B server.
;Hibernate is a rame which is used to interact with database
server&
*here are so many "rame#orks are available in the market there are
some o" struts, srin!s, 2SA etc.
+. Struts, srin! "rame #orks are used to develo #eb-based
alications.
2. Hibernate is a technolo!y are a "rame#ork #hich is used to interact
#ith database server this "rame#ork resolves all the roblems o"
2
2'BC. In a ro$ect i" he tries to use hibernate "rame #ork i" he
develo the ro$ect )uickly.
-. %s art o" 2'BC #e have to #rite lot o" code to hardly checked
(7cetion.
/. %s art o" Hibernate #e no need to rovide the code to handle
checked (7cetion.
1. I" #e use 2'BC a ro!rammer is resonsible to re!ister the driver
and !et the connection. Pro!rammer must rovide the code to close
the connection. %s art o" Hibernate he is resonsible to oen the
connection and close the connection.
D. %s art o" Hibernate it8s only starts the transaction and ends the
transaction. Hibernate internally uses 2*% (2ava *ransaction %PI). *o
start the transaction and end the transaction.
E. Hibernate suort internal connection rovides Hibernate uses C-B
connection ool. 'BCP connection ool. I" #e #ent to use e7ternal
connection ool like #eb-lo!ical #e can con5!ure it. I" #e use 2'BC
#e have to rovide the code to handle database seci5c error code.
F. I" #e use Hibernate #e no need to rovide the code to handle
database seci5c errors.
G. Hibernate suorts it8s o#n )uery lan!ua!e H?@ (Hibernate ?uery
lan!ua!e) to resolve the roblems o" some $ava alication to
interact #ith multile 'B Servers #ithout chan!in! the )ueries.
+H. In case o" 2'BC #e have to rovide the code to remove the hard
codin!. In case o" Hibernate #e rovide the details in Hibernate
con5!uration by readin! the details "rom con5!uration 5le (.I,@). It
#ill interact #ith multile 'atabase Server.
++. I" #e use 2'BC ro!rammer is resonsible to #rite the code to
!enerate the rimary key values. %s art o" Hibernate they have
rovided re-de5ned class to !enerate rimary key values.
+2. By usin! Hibernate #e can reresent the )ueries in the "orm o"
ob$ect or #e can use criteria %PI. %s art o" Hibernate #e can
achieve olymorhism bet#een the tables and #e can achieve
association also.
+-. ;by usin! 2'BC #e can8t trans"er result set ob$ect "rom one
ro!ram to another ro!ram (result set can8t be trans"erable) to
resolve this roblem #e have to rovide the code to retrieve data
"rom result set ob$ect and store it in array list ob$ect i" #e use
Hibernate. Hibernate does all these #ork.
2
+/. ;#e have the technolo!y like (2B to interact #ith 'B Server #e
can8t run (2B %lication #ithout (2B container. 6e can8t use (2B8s in
all tye o" alication #e can resolve all these roblems #e can use
Hibernate.
;*he "ollo#in! is true %rchitecture o" Hibernate "rame#ork.
;Hibernate is called as >0, tool are >0, "rame#ork >0, (>b$ect
0elational ,ain!).
In the market they are so many >0, "rame #orks are available some o"
them are Hibernate, 2P% ($ava ersistent %PI) 2'> ($ava data ob$ect) i
batches, S*> (service data oC), *o @ink etc.
%ll these "rame #orks are used as >0, *ools. *he diJerences bet#een
the *ools are the names o" the classes are diJerent.
In the database server the data #ill be stored in the side the tables
bet#een the tables #e establish a relationshi because o" this reason #e
call it is relational data.
;0eresentations relational records in the "orm o" ob$ect #e call it has
>0,&
Hibernate SC6
2%K% %lication
2'BC %PI
db
'B Server
+
Pone
+HH
2
Product
;can #e use 2'BC to reresent records in the "orm o" ob$ectL
%. Bes, #e can use 2'BC to reresent the records in the "orm o" ob$ect.
In case o" 2'BC #e have to rovide hu!e amount o" code to
reresent hu!e amount o" data in the "orm o" ob$ect.
B. %s a Hibernate develoer #e need to develo a $ava alication
#ith uses Hibernate %PI and interact #ith database server. I" #e
#ant to develo a $ava alication #e need to con5!ure 'B server
and rovide some additional 5les to Hibernate so"t#are.
C. I" the Hibernate so"t#are to communicate #ith database server #e
re)uired a user #ith secial rivile!ed (se)uence) the tables in the
database server must contain rimary keys.
;Procedure to create user and assign some privileges&
+. @o!in to database server usin! administrative user use the
"ollo#in! command assi!n the user and rivile!es.
S?@M create user hib ide5ed br abcN
9rant connect, resource to hibN
9rant create se)uence to hibN
2. 6e have to create the table #ith rimary key.
S?@M create table em (eno number(/) rimary key, ename
varchar2(2H),
%ddress varchar2(2H))N
S?@M create table roduct (id number(1), name varchar2(2H),
rice number(+H,2))N
S?@M alter table roduct add rimary key(id)N
-. 6e can !et Hibernate so"t#are "rom Hibernate.or!
/. Hibernate so"t#are is a collection o" $ar 5les the most imortant $ar
5le is Hibernate.$ar
1. I" #e #ant to use Hibernate so"t#are #e have to develo the
"ollo#in! - 5les.
+ Pno +HH
2 name
2HHH
- rice
-HHH
2
P*#o
2HHH
2
1.+. Hibernate con5!uration 5le
1.2. 2ava Beans (P>2> classes) (lain >ld 2ava >b$ect)
1.-. Hibernate ,ain! 5les (hbm)
D. (very "rame#ork uses con5!ure 5le. *his is the startin! oint to
any "rame#ork !enerally the con5!uration 5les or 7ml 5les(#e can
use roerty 5les also as con5!uration 5les)
E. ;in Hibernate #e use Hibernate.c"!.7ml as the con5!uration 5le #e
can chan!e the con5!uration 5le name accordin! to re)uirement.
F. Hibernate con5!ure 5le contains the entire in"ormation #hich is
re)uired to communicate #ith database server. *hey are&
a. 'river class
b. url
c. username
d. #d
e. dialect
Hibernate.c"!.7ml
G. Hibernate so"t#are re)uired the $ava ro!ram to reresent a record
in the "orm o" ob$ect. Because o" this reason #e have to develo
coule o" $ava ro!rams this is based on the number o" tables
available in the database server.
+H. *hese ro!rams contains instance variables, set0o#() and
!er0o#() methods. 'eveloin! these ro!rams are easy because o"
this reason P>2> classes are kno#n as (lain old $ava ob$ects).
++. In our database server #e have t#o tables em and roduct. 6e
need to develo t#o o$o classes.
a. (m.$ava
b. Product.$ava
Note& *here is no rule sayin! rotocol names and tables name
must be same.
driverOclass Poracle.$dbc
url P $dbc.oraQ.
username P hib
ass#ord P abc
dialect P >racle'ialect
CCin"ormation about H0, 5les
ublic class emloyeeR
int enoN
strin! enameN
strin! eddressN
ublic void set(no(int eno)
R
this.eno P enoN
S
ublic int !et(no()R
return enoN
S
2
+2. 6e have to develo Hibernate main! 5les. *hese 5les contain.
*he in"ormation about #hich rotocol class is maed #ith #hich
table and #hich roerties maed #ith #hich column.
em.hbm.7ml
Note&
I'( takes care o" !eneratin! Hibernate con5!uration 5le, o$o
classes and Hibernate ,ain! 5les.
;!he P"#" classes must ollowing rules&
+. ,ust contain a de"ault constructor.
2. ,ust be laced inside a acka!e.
-. *he P>2> class suorts roerties. % set0o#() and !et0o#()
methods are called as roerties.
/. 6hen the Hibernate eole are develoin! so"t#are they are
started usin! the hel o" other so"t#are8s. *hey are like *ransaction
%PI, Connection *ool, 'om Parse, cache $ar 5les. I" #e #ould like to
run the Hibernate so"t#are are need to make sure that all these $ar
(mloyee (m
(P>2>) (*able)
(,P.> (.>
(,P.%,( .%,(
(,P%''0(SS %''0(SS
2
5les !enerate the C@%SSP%*H other #ise Hibernate so"t#are #ill "ail
to run.
Hibernate SC6
QQQ.. (tc
;;;Procedure to con5!ure the Hibernate so"t#are and !enerate Hibernate
con5!uration 5le by usin! ,y(clise I'(.
I. Start ,y(clise I'( ointin! to #orks lace "older.
II. Con5!ure ,y(clise I'( to interact #ith the 'B Server.(create 'B
Bro#ser)
III. Create a $ava ro$ect and add the acka!e to it.
IK. %dd Hibernate caabilities to the above ro$ect. ,y(clise
ro$ect caabilities
Hibernate caabilities.
K. Choose the re)uired $ar 5les to be added. (Core library and notations).
KI. Choose ne# Hibernate con5!uration otion and click on ne7t button.
Arom the list o" available 'B 'river select to #hich database server
#e have to connect.
KII. Choose the acka!e name and rovide the class name as >0%SA and
click on 5nish button.
;Procedure to generate hbm fles and P"#" classes&
Ste +& 9o to ,y(clise db e7lorer ersective and establish the
connection #ith 'atabase server.
Hibernate-.$ar
2*%.$a
r
C-P.$
ar
'om.$
ar
Cach
e.$ar
2
Ste 2& Select the all re)uired tables and ri!ht click on it !enerates T
launch o-u menu "rom that choose on otion Hibernate reverse
(n!ineerin!.
Ste -& Select src and acka!e and check the 5rst - check bo7es and
click on 5nish button launches abstract class.
Ste /& *he "ollo#in! is the con5!uration is Hibernate con5!uration 5le.
Uhibernate-Con5!urationM
USession-AactoryM
Uroerty name P 3Connection.driverOclass4M
oracle.$dbc.driver.>racle'river
UCroertyM
Uroerty name P 3Connetion.url4M
$dbc&oracle&thin&Tlocalhost&+12+&7eUCroertyM
Uroerty name P 3Connection.username4MhibUCroertyM
Uroerty name P 3dialect4Mor!.hibernate.dialect
>racleGi'ialectUCroertyM
Umain! resource P 3in"oCinetsolvCroduct.hbm.7ml4CM
Uma resource P 3in"oCinetSolvC(m.hbm.7ml4CM
UCSession-AactoryM
UChibernate-con5!urationM CC Save hibernate.c"!.7ml
Ste 1& *he "ollo#in! is the P>2> class o" em tables.
ublic class (mR
rivate Inte!er enoN
rivate Strin! nameN
rivate 'ouble salaryN
CC rovide setters and !etters methods
above instance variables.
S CC Save (m.$ava
Ste D& *he "ollo#in! on the ta!s o" (mloyee 5le.
Uhibernate main!M
2
Uclass name P 3in"o.inetsolv.(m4 table P 3(m4M
Uid name P 3eno4 tye P 3$ava.lan!.Inte!er4M
Ucolumn.name P 3(.>4 resission P 3s4CM
U!enerator class P 3assi!ned4CM
UCidM
Uroerty name P 3name4 tye P 3$ava.lan!.Strin!4M
Ucolumn name P 3.%,(4CM
UCroertyM
Uroerty name P 3salary4 tye P 3$ava.lan!.'ouble4M
Ucolumn name P 3S%@%0B4CM
UCroertyM
;*he "ollo#in! are the most imortant inter"aces and classes.
;Interaces&
+. or!.hibernate.SessionAactory
2. or!.hibernate.Session
-. or!.hibernate.*ransaction
/. or!.hibernate.?uery
1. or!.hibernate.Criteria
;$lasses&
+. or!.hibernate.c"!.Con5!uration
;*he "ollo#in! are the stes #hich #ill be used to develo Hibernate
alication.
+) Create Con5!uration >b$ect.
2) Call the Con5!uration() method by usin! the Con5!uration >b$ect.
-) 9et SessionAactory >b$ect by usin! Con5!uration >b$ect, #e use a
method build SessionAactory().
/) 9et Session >b$ect by usin! SessionAactory. Call the method
oenSession().
1) 9et the *ransaction >b$ect.
D) Create the P>2> class >b$ect #hich #e #ould like to er"orm the
>erations.
E) Store the data in the P>2> class >b$ect.
F) Call the methods saveCudateCdeleteCload methods.
G) (nd *ransaction by usin! commitCrollback.
+H) Close Session >b$ect.
2
++) Close SessionAactory >b$ect.
;%e&uirement&
'evelo a Hibernate alication to insert records in to the em table.
*he "ollo#in! is the $ava code #hich is used to store the data into em
table.
ublic class Store(m'etailsR
ublic static void main(Strin! ar!sVW)R
Con5!uration c"! P ne# Con5!uration()N
c"!.con5!ure()N
SessionAactory s" P c"!.buildSessionAactory()N
Session hsession P s".oenSession()N
*ransaction t7 P hsession.be!in*ransaction()N
(m e P ne# (m()N
e.set(no(+)N
e.set.ame(30a$u4)N
e.set%ddress(3Hyd4)N
hsession.save(e)N
t7.commit()N
hsession.close()N
s".close()N
S
S
Note&
6hen #e 0un the same alication "or t#o times #e !ot an
(7cetion sayin! that ConstraintKiolation(7cetion.
+. 6hen #e create the con5!uration ob$ect #e are create an
environment to store the con5!uration details. In this con5!uration
ob$ect #e can store 'river class, url, username, ass#ord and
main! in"ormation.
2. 6hen #e call c"!.con5!ure it checks "or hibernate.c"!.7ml 5le in the
C@%SSP%*H. I" it is available it start readin! the contains "rom
hibernate con5!uration 5le. .o# the hibernate 5le the
corresondin! hbm 5les it oens all the hbm 5les and try to read
2
the contents "rom all hibernate main! 5les. %ll this in"ormation
stored a 2K,8s memory (con5!uration ob$ect). I" the con5!uration
ob$ect not available in the class ob$ects it thro# (7cetion
or!.hibernate.hibernate(7cetion.
Note&
*his method is an (7ensive oeration. In a ro$ect it is
recommended to call the con5!ure method only once in the ro$ect li"e
cycle.
ublic class Store(m'etailsR
ublic static void main(Strin! ar!sVW)R
Con5!uration c"! P ne# Con5!uration()N
c"!.con5!ure()N
SessionAactory s" P c"!.buildSessionAactory()N
Session hsession P s".oenSession()N
*ransaction t7 P hsession.be!in*ransaction()N
(m e P ne# (m()N
Product P ne# Product()N
e.set(no(+)N
e.set.ame(30a$u4)N
e.set%ddress(3Hyd4)N
.setId(+)N
.set.ame(30ice4)N
.set%mount(+HHH)N
hsession.save(e)N
hsession.save()N
t7.commit()N
hsession.close()N
s".close()N
S
S
*his method is an e7ensive oeration in a ro$ect it is recommended to
call the con5!ure method only once in the ro$ect li"e cycle.
In any "rame #rote #e can chan!e the con5!uration 5le name accordin!
to our re)uirement.
2
I" you are usin! our o#n con5!uration 5le name #e have to use the over
loaded con5!uration method.
Ex& c"!.con5!ure(3myro$ect.7ml4)N
Note&
*he de"ault con5!ure method al#ays check "or hibernate c"!.7ml
5le. It al#ays recommends usin! .c"! in the con5!uration 5le name.
Because o" this #e can easily reco!niXe the con5!uration 5le name.
hibernate.c"!.7ml
;.hbm.7ml
6hen #e call c"!.build SessionAactory() method it !ets driver class, url,
username and ass#ord these values are sulied as inut to hibernate
internal connection ool. .o# the hibernate internal connection ool. 9et
the connections "rom database servers.
.o# the build SessionAactory method !ets a connection "rom connection
ool and establish the connection #ith database server. It #ill check
#eather all the re)uired tables are available or not. I" not available i"
re)uired build SessionAactory() method create the tables. It is the
resonsibility o" hibernate build SessionAactroy() to create all the <CY0'8
)ueries "or every table and store the )ueries in 2K,8s memory no# the
build SessionAactory close the connection.
con5!uration()N
2
Note& callin! build SessionAactory() method reeatedly in the ro$ect is
not recommended. It is recommended to call only once in li"e time o" the
ro$ect.
By de"ault build SessionAactory() method is not cratin! the tables. I" you
#ant to hibernate to create the tables #e have to suly an additional
roerty <hbm2 ddl.auto8 these roerties can take any o" the "ollo#in!
"our values create, udate and create-delete, validate.
*he "ollo#in! is the ta! #hich has to be added to Hibernate con5!uration
5le.
Uroerty name P 3hbm2ddl.auto4MudateUCroertyM
It is al#ays advisable to !et a session >b$ect #hen ever #e #ould like to
carry out any #ork by usin! Hibernate. It8s al#ays recommended to close
the session >b$ect a"ter #e 5nish the #ork. 9ettin! a session ob$ect to
similar to !ettin! a connection ob$ect in 2'BC.
6hen ever the session ob$ect is created immediately Hibernate starts a
cache ob$ect and it #ill be associated to session ob$ect are all this cache
ob$ects as +
st
level cache Hibernate remove the cache ob$ect #hen ever
#e close the session ob$ect.
%rrays #e have to start transaction a"ter the session ob$ect is created.
6e need to start the transaction only "or insertCudateCdelete oeration
only. 6e no need to start the transactions "or retrieve the records.
6hen #e call hsession save hibernate takes the ob$ect and add it to 5rst
level cache by usin! a re!istration code is 3*BS4 to be save.
Cache
session
eno& +
name& abc
address&
hyd
*BS
2
6hen #e call 3t7.commit4 hibernate !ot 5rst level cache and check are
there any ob$ect are available in 5rst level cache it the ob$ects are
available hibernate check. *he re!istration code o" the ob$ect hibernate
5nd to #hich P>2> class this ob$ect is created and to #hich table this
P>2> class is maed.
Based on the table name and re!istration and hibernate !et the insert
)uery "rom the 2K,8s memory. It is the resonsibility hibernates to
relace ositional arameters #ith aroriate values "rom the ob$ect.
.o# the hibernate add the )uery to batch ob$ect.
.o# the hibernate send the batch ob$ect to 'atabase server i" it !ot
e7ecute success"ully it returns an identi5es value. I" the batch is "ailed it
thro#s an e7cetion batch udate e7cetion.
Hibernate send a s)l )uery to 'atabase server to see the s)l )uery sent
by hibernate #e can add roerty 3sho#-s)l4. *his attribute takes a
Boolean value.
Ex&
Uroerty name P 3sho#Os)l4MtrueUCroertyM
*o see all the messa!es are #ork done by hibernate #e can use
lo!/$.roerties.
6e can use a method 3ersist4 to store the data into database server.
'(ntax& void ersist(ob$ect)
Ex& serialiXable save(ob$ect)
6hen #e !enerate hbm 5les and P>2> classes in hibernate by usin! I'(
based on the column data tye I'( !enerate the aroriate data tye in
P>2> class "or e7amle eno number(+1) I'( uses bi! decimal data tye
"or eno number(2) I'( uses byte and etc.
lo!/$.root lo!!er P '(BY9C%+
lo!/$.aender.%+ P or!.%P%che.lo!/$.console
%ender
lo!/$.aender.%+.layout P
2
%s art o" $ava1.H sun micro system as added a "eature auto bo7in!. *he
advanta!e o" auto bo7in! is #e @%. directly convert rimitive data tye
values to #raer classes.
Ex&
int a P +HN
inte!er i P aN
system.out.rintln(i)N
6hen #e tryin! to dual #ith auto bo7in! "or double data tye as sho#n
belo# #e are !ettin! the comilation error.
Ex& 'ouble d P 2HdN
;develo a Hibernate alication to retrieve a record "rom em table
#here eno is 2L
ublic class 0etrieve0ecordsR
ublic static void main(Strin!VW ar!s)R
Con5!uration c"! P ne# Con5!uration()N
c"!.con5!ure()N
SessionAactory s" P c"!.buildSessionAactory()N
Session hsession P s".oenSession()N
(m e P ne# (m()N
Hsession.load(e,ne# Bi!decimal(2))N
System.out.rintln(3e.!et(no())N
System.out.rintln(3e.!et.ame())N
System.out.rintln(3e.!etSalary())N
hession.close()N
S
S
6hen #e call the load() method the internal code o" Hibernate has
er"ormed the "ollo#in! stes.
Ste +& It has checked the corresondin! P>2> class name "or the
sulied ob$ect.
2
Ste 2& It has checked this P>2> class ob$ect is maed to #hich table "or
that table Hibernate has icked aroriate select )uery. *he "ollo#in! is
the )uery available in 2K,8s memory.
Select eno, name, salary "rom em #here eno PL .o# the
Hibernate has relaced the ositional arameter value #ith 2 and
send the )uery to database server.
'atabase server has e7ecuted the select )uery and reresented the
records in the result set ob$ect and !iven into hibernate so"t#are.
Hibernate so"t#are has taken "rom 0esultSet ob$ect and by usin!
the !etter method !ot the data "rom 0esultSet ob$ect and stored it
in P>2> class ob$ect.
.o# the Hibernate added the P>2> class ob$ect to +
st
level cache.
Note& I" #e try to call a load cs method on a non available record
Hibernate thro# an e7cetion sayin!
<or!.hibernate.>b$ect.otAound(7cetion8.
*o check #eather any ob$ect is available in +
st
level cache or not #e can
use a method <contains()8.
'(btax& boolean Contains(ob$ect)
;6rite a hibernate alication to delete the records "rom roduct table
#hose roductI' is ++.*o delete the records "rom hibernate #e can use
t#o aroaches.
)pproach *& @oad the record and mark the ob$ect as to delete.
ublic class 'elete0ecordsR
ublic static void main(Strin!VW ar!s)R
Con5!uration c"! P ne# Con5!uration()N
c"!.con5!ure()N
SessionAactory s" P c"!.buildSessionAactory()N
Session hsession P s".oenSession()N
*ransaction t7 P hsession.be!in*ransaction()N
Product P ne# Product()N
hsession.load(,++)N CC ste +
hsession.delete()N CC ste 2
t7.commit()N CC ste -
2
hsession.close()N
S
S
Ste +& #hen ste + is e7ecuted it has retrieve the records #hose
rimary key value is ++ and add into +
st
level cache.
Ste 2& 6hen #e call the method ob$ect is marked as to be deleted.
Ste -& #hen #e call the commit method the hibernate so"t#are !ot the
delete )uery and relaces the ositional arameter #ith rimary key
value and send the )uery to database server.
In this aroach 5rst #e are checked in #hether the record is available or
not i" the record is not available. *he load() method thro#s ob$ect not
"ound e7cetion.
)pproach +& Create the P>2> class ob$ect and suly the rimary key
value. ,ark the P>2> class ob$ect as to be deletin! by callin! the delete
method.
Ex&
ublic class 'elete0ecords+R
ublic static void main(Strin!VW ar!s)R
Con5!uration c"! P ne# Con5!uration()N
c"!.con5!ure()N
SessionAactory s" P c"!.buildSessionAactory()N
Session hsession P s".oenSession()N
Product P ne# Product()N
.setid(++)N
hsession.delete()N
t7.commit()N
hsession.close()N
S
S
In this aroach #hen #e call the delete method ob$ect is marked as to
be deleted. 6hen #e call the commit() method it has er"orm the
"ollo#in! - stes.
2
Ste +& It check #eather rimary key value is available in the sulied
ob$ect or not. I" not available it #ill not carry out any #ork.
Ste 2& I" the rimary key value is available a select )uery #ill be send to
database server to check #eather record is available or not.
Ste -& I" the record is available in 'B hibernate send the delete )uery. I"
the record is not available hibernate #ill not do any #ork.
)pproach *& Ydatin! a record into database server #hich ever the
record #e #ould like to udate load the record by callin! load() method
modi"y the values by usin! setter methods in the loaded P>2> class
ob$ect. .o# mark the ob$ect as to be udated.
Ex&
ublic class Ydate0ecordR
ublic static void main(Strin!VW ar!s)R
Con5!uration c"! P ne# Con5!uration()N
c"!.con5!ure()N
SessionAactory s" P c"!.buildSessionAactory()N
Session hsession P s".oenSession()N
(m e P ne# (m()N
hsession.load(e, ne# Bi!'ecimal(2))N
e.set.ame(30a$u4)N
hsession.udate(e)N
t7.commit()N
hsession.close()N
S
S
)pproach +& Hibernate uses a directory ob$ect techni)ue to check
#eather ob$ect value is modi5ed or not. I" the value is not modi5ed.
Hibernate #ill not send any udate )uery to the database server. I" the
values are modi5ed Hibernate send an udate )uery to database server.
)pproach ,& In this aroach create P>2> class ob$ect to the class #hich
#e #ould like to udate the record and store the data into P>2> class
ob$ect. 6e need to mark the ob$ect as to be udated.
Ex&
2
ublic class Ydate0ecordR
ublic static void main(Strin!VW ar!s)R
Con5!uration c"! P ne# Con5!uration()N
c"!.con5!ure()N
SessionAactory s" P c"!.buildSessionAactory()N
Session hsession P s".oenSession()N
(m e P ne# (m()N
e.set(no(ne# Bi!'ecimal(2H))N
e.set.ame(3ttt4)N
hsession.udate(e)N
t7.commit()N
hsession.close()N
S
S
;evict()& evict() method is used to remove a seci5ed ob$ect "rom the +
st
level cache.
Ex&
*ransaction t7 P hsession.be!in*ransaction()N
hsession.load(e,ne# Bi!'ecimal(+))N
e.set.ame(30a$u4)N
hsession.evict(e)N
t7.commit()N
6hen #e run the above alication #ith out evict() method. It has
udate a record into database server. 6hen #e run the some alication
#ith evict() method. It has removed emloyee ob$ect "rom +
st
level
cache.
;merge()& mer!e method is used to add a seci5ed ob$ect to the +
st
level cache.
Ex&
(m e P ne# (m()N
e.set(no(ne# Bi!'ecimal(22))N
e.set.ame(3%BC modi5ed4)N
e.setSalary(+2-/d)N
2
hsession.mer!e(e)N
t7.commit()N
6hen the mer!e() method is called the ob$ect is added to +
st
level cache
#ithout re!istration code. 6hen t7.commit() method is called it #ill !et
the ob$ect #hich does not contain the re!istration code. It #ill check
#eather the ob$ect is available in database server by sendin! select
)uery. I" the record is not available it #ill send an insert )uery to
database server. I" the record is already available it #ill send a an udate
)uery to database server.
;*here three states are available to hibernate ob$ects they are&
+. *ransient
2. Persistent
-. 'etached
!ransient& %n ob$ect is #hich is not associated #ith any session ob$ect.
Persistent& %n ob$ect #hich is added to +
st
level cache is called as
ersistent state.
Detached& %n ob$ect #hich is removed "rom +
st
level cache is called
detached state.
;$lear()&
Clear is used to remove all the ob$ects "rom +
st
level cache.
*his #ill remove uner"ormed oerations like save and udate also. *he
clear() method #ill evict all available ob$ects.
;$onnection()&
*his method is used to !et le!acy database connection.
9enerally this is not recommended aroach in hibernate. 6e use this to
er"orm some oerations #hich can not be done by usin! hibernate.
Ex&
Session hsession P s".oenSession()N
*ransaction t7 P hsession.be!in*ransaction()N
Connection con P hsession.Connection()N
Statement stmt P con.createStatement()N
stmt.e7ecuteYdate(3Insert into em values(2,8sada"8,2-/)4)N
2
t7.commit()N
In Hibernate #hen #e !et the connection ob$ect by de"ault auto commit
mode to "alse.
6e have multile over loaded methods as "or session inter"ace they are&
void load(ob$ect, id)
ob$ect load(class, serialiXable)
Ex&
Class c P class."or.ame(3in"o.inetsolv.roduct4)N
>b$ect o P hsession.load(c,l)N
Product P (roduct)oN
System.out.rintln(.!etPid())N
System.out.rintln(.!et.ame())N
System.out.rintln(.!etPrice())N
6hen #e call the above load() method i" the record is available load()
method creates P>2> class ob$ect and store the data and return P>2>
class ob$ect i" the record is not available load() method #ill not create
P>2> class ob$ect.
6e have a static variable class as art o" ob$ect class #hen ever #e call
that variable by usin! class name it returns the callin! class classob$ect.
Ex&
Cone.class
6hen the above code is e7ecuted it has return class ob$ect.
Class
;get()&
!et() method is also used to retrieve the record "rom database server i"
the record is available it returns that P>2> class ob$ect. I" record is not
available it returns null value.
name P
Cone
acka!e P
null
2
Ex&
>b$ect o P hsession.!et(roduct.class,2)N
I"(oZ P null)R
Product P (roduct)oN
System.out.rintln(.!etPid())N
System.out.rintln(.!et.ame())N
System.out.rintln(.!etPrice())N
S
elseR
System.out.rintln(30ecord is not available4)N
S
;-ush()&
6hen #e call in [ush() method all the ob$ects #hich are
available in +
st
level cache #ill be converted into )ueries and send to
database server. Alush #ill not store data ermanently. 6hen #e all the
commit() method the data is stored ermanently.
[email protected] roerty takes by diJerent values
+. Ydate
2. Create
-. Create-dro
/. Kalidate
I" hbmaddl.auto P udate and #eather the buildSession"ctory() method
is e7ecuted it checks #eather tables are available or not. I" not available
it create the takes.
I" hbmaddl.auto P create i" the tables are not available
buildSessionAactory() method creates it. I" the takes and create a!ain i"
hbmaddl.auto P create-dro i" the tables are not available it creates the
tables. #hen #e close the session "actory ob$ect the tables #ill be
droed.
I" hbmaddl.auto P validate, buildSessionAactory() method check #eather
the tables are resent in the database server or not. I" not available it #ill
thro# an error messa!e missin! table.
;Developing Hibernate application b( using manual procedure&
2
*he "ollo#in! is an architecture o" hibernate alication.
Ste +& Create a table in the data base server.
Ste 2& 9et the Hibernate so"t#are and laced in a lib "older (coy
o$dbc+/.$ar also).
Note&
6e can !et the $ar 5les "rom I'(.
Ste -& 'evelo a cmd 5le #hich contains the class ath to all the
Hibernate related $ar 5les.
Ex& Set C@%SSP%*HPlib\antlr.2.E.D.$arNlib\C-PH-H.G.+.$arN
Ste /& Create the P>2> class. 6e can use any class name as P>2> class
name "or e7amle.
ublic class (mloyeeR
int em.oN
Strin! em.ameN
double emSalaryN
ublic void set(mloyee.o(int emloyee.o)R
this.em.o P emloyee.oN
S
ublic int !et(mloyee.o()R
return emnoN
S
;Create hbm 5le the name o" hbm 5le can be any thin!.
2ava alication
Hibernate SC6
Hibernate.roerties
or
Hibernate.c"!.7ml
'atabase Server
2
UL7ml version P 3+.H4LM
UZ '>C*BP( hibernate.main! ublic 3somethin!4
3htt&CC###.hibernate.or!CdtdChibernate-main!--.Hdtt4M
Uhibernate-main!M
Uclass name P 3in"o.inetsolv.(mloyee4table P 3em4M
Uid name P 3emloyee.o4M
Ucolumn name P 3eno4CM
U!enerator class P 3assi!ned4CM
UCidM
Uroerty name P 3emloyee.ame4M
Ucolumn name P 3name4CM
UCroertyM
QQQQQQQQQQ.
UCclassM
UChibernate-main!M
;'evelo hibernate con5!uration 5le.
UL 7ml version P 3+.H4LM
UZ '>C*BP( hibernate-con5!uration ublic 3hibernate-con5!uration4,
4htt&CC###.hibernate.or!CdtdChibernate-con5!uration-
-.H.dtt4M
Uhibernate-con5!urationM
Usession "actoryM
QQQQQQQQQQQ.
UCsession "actoryM
UChibernate-con5!urationM
'evelo a $ava alication to store the data into database server.
*he arser ro!ram check "or hibernate dtd 5le as art o" hibernate 5le.
%s art o" hbm 5le #e can remove the column ta! or attribute i" the P>2>
class roerties and column names are same.
;*he "ollo#in! is samle con5!uration "or em table.
Uhibernate-main!M
Uclass name P 3in"o.inetsolv.(mloyee4M
Uid name P 3emloyee.o4CM
Uroerty name P 3emloyee.ame4CM
2
Uroerty name P 3emloyeeSalary4CM
UCclassM
UChibernate-main!M
6e can club multile hbm 5les into a simle hbm 5le. But this aroach
is not recommended "or bi! ro$ects, it is recommended to use one hbm
5le Br>ne one P>2> class.
Uhibernate-main!M
Uclass name P 3in"o.inetsolv.(mloyee4M
Uclass name P 3in"o.inetsolv.Product4M
Uid name P 3Pid4 access P 35eld4CM
Uroerty name P 3name4 class P 35eld4CM
UCclassM
UChibernate-main!M
6e can develo hibernate alication #ith out hibernate con5!uration
5le. But #e have to rovide the roerties and main! 5les throu!h the
$ava ro!ram.
Ex&
ublic class StoreR
ublic static void main(Strin!VW ar!s)R
Con5!uration c"! P ne# Con5!uration()N
c"!.setProerty(3hibernate.connection.driverOclass4,4oracle.$dbc.driver.>r
acle'river4)N
c"!.setProerty(3hibernate.connection.url4,4$dbc&oracle&thin&Tlocalhost&+
12+&7e&4)N
c"!.setProerty(3hibernate.connection.username4,4hib4)N
c"!.setProerty(3hibernate.connection.ass#ord4,4abc4)N
c"!.setProerty(3hibernate.dialect4,4or!.hibernate.dialect.>racleG'ialect
4)N
c"!.setProerty(3hibernate.sho#Os)l4,4true4)N
c"!.add0esource(3a.hbm.7ml4)N
sessionAactory s" P c"!.buildSessionAactory()N
session hession P s".oenSession()N
QQQQ
QQ..
2
Q.
S
S
Instead o" add0esource() method #e can use addClass() method.
Ex&
c"!.addClass(in"o.inetsolv.roduct.class)N
#hen #e use addClass() it #ill check "or in"o.inetsolv.roduct.hbm.7ml
5le.
*he disadvanta!e o" ro!rammatic con5!uration is #hen Hard codin!
the values in the $ava ro!ram. I" #e #ant to communication #ith same
hibernate alication #ith diJerent database server. 6e have to chan!e
the $ava code because o" this reason this aroach is not recommended.
9enerally in the ro$ects #e use roerties 5les to remove hard codin!.
,ost o" the ro$ects uses roerty 5le end #ith an e7tension dot (.)
roerties inside the roerties 5le #e suly a data in the "orm o" key
and value.
Ex&
:ey P value CCmyro$ect.roerties
6e can con5!uration hibernate arameters as art o" a roerty-5le.
6ho8s name is hibernate roerties.
Ex&
hibernate.connection.driverOclass P oracle.$dbc.driver.>racle'river
hibernate.connection.url P $dbc&oracle&thin&Tlocalhost&+12+&7e
hibernate.connection.username P hib
hibernate.connection.ass#ord P abc
hibernate.dialect P or!.hibernate.dialect.>racleG'ialect
hibernate.sho#Os)l P true
CCsave hibernate.roerties
It8s not recommended to use roerty 5le as art o" hibernate. *his is
because as art o" the roerty 5le are can8t con5!uration the main!
resource 5les.
6e can suly the values by the roerties usin! system roerties
#hen #e run the alication.
2
Ex& -'hibernate.connection.driverOclass P oracle.$dbc.driver.>racle'river
,ea!erly hibernate is divided into three arts. *hey are&
Hibernate SC6
Hibernate SC6 is !ood at >0, as #ell as transaction mana!ement the
internal hibernate code uses t#o connections ools C-P, 'BCP. It8s not
recommended to use there connection ools. It8s al#ays recommended
to use the e7ternal connection ool like weblogic connection ool.
;Ysin! rocedure to use #eblo!ic connection ool ro!ram in hibernate.
+. Con5!ure #eblo!ic server connection ool by seci"y 2.'I name.
2. 9et the hibernate SC6 lace in lib "older and set the class ath.
-. Create P>2> class and hbm 5le.
/. Create hibernate con5!uration 5le #ith data source, username and
ass#ord and $ndi.class and $ndi.url
Uhibernate-con5!urationM
USession-AactoryM
Uroerty
nameP3hibernate.connection.datasource4MmyoolUCroertyM
Uroery
nameP3hibernate.connection.username4MadminUCroertyM
Uroery
nameP3hibernate.connection.ass#ord4MinetsolvUCroertyM
Uroery
nameP3hibernate.$ndi.class4M#eblo!ic.$ndi.6@InitialConte7tAactory
UCroertyM
Uroery
nameP3hibernate.$ndi.url4Mt-&CClocalhostEHH+CUCroertyM
Uroery nameP3hibernate.sho#Os)l4MtrueUCroertyM
Umain! resource P 3a.hbm.7ml4CM
Connection ,ana!ement
>0,
*ransaction ,ana!ement
2
UCSession-AactoryM
UChibernate-con5!urationM
1. 'evelo the hibernate alication to store the data into database
server.
Note& #e have set the class ath to #eb.$ar or set 'omain(nv.cmd
D. 6hen #e are con5!uration are usin! connection ool as art o"
hibernate #e have choose use $ndi data source rather then $dbc
driver.
E. *o set the class ath to resolve the roblem o"
#eblo!ic.$ndi.6@InitialConte7tAactory #e are added #eblo!ic.$ar in
the class ath.
F. Hibernate can be used to communicate #ith any 'B server.
;Procedure to develop hibernate application to interact with
./'01&
6hen #e communicate #ith ,BS?@ 'B Server. 6e have chan!e the url,
username, driver class and etc.
6e have to al#ays use 3#raer classes2 as art o" P>2> classes instead
o" rimitive data tyes. Primitive data tyes occuy less amount o"
memory #hen comared #ith #raer classes. Primitive data tyes can8t
hold a null value.
Ex& ublic class ,y%R
ublic static void main(Strin!VW ar!s)R
int a P nullN
System.out.rintln(a)N
S
S
6hen #e comile the above ro!ram the comiler reorts error messa!e
sayin! null value can not be assi!ned to rimitive data tyes. #e can
assi!ned a null value to #raer classes.
Ex&
ublic class ,y%R
ublic static void main(Strin!VW ar!s)R
Inte!er a P nullN
System.out.rintln(a)N
S
S
2
%s art o" the I'( #hen #e !eneratin! hbm 5les and P>2> classes #e
have an otion. 6e have rimitive data tyes or #raer classes. *hey
are $ava tyes and hibernate tyes.
6hen #e choose $ava tyes it uses #raer classes. 6hen #e choose
hibernate tyes it uses rimitive data tyes.
6e are try to use rimitive data tyes and tryin! to store data into
tables. In these scenarios the de"ault values o" rimitive data tyes are
!ettin! store into data base server.
Ex&
Product P ne# Product()N
.setPid(Pid)N
.set.ame(Pname)N
hsession.save()N
6hen #e e7ecute the above code even thou!h #hen the user is not
sulied rice value alication has stored H.H values.
6hen #e use rimitive data tyes to retrieve records "rom a table #hich
contains null values. then the alication thro#in! an e7cetion.
3org3hibernate3propert()ccessExcepton4.
By usin! 2'BC also #e can reresent the records in the "orm o" ob$ects.
*he "ollo#in! is an e7amle o" reresentin! data in the "orm o" ob$ect by
usin! 2'BCL
Ex&
0esultSet rs P stmt.e7ecute?uery(3select ; "rom roduct4)N
%rray@ist list P ne# %rray@ist()N
6hile(rs.ne7t())R
Product P ne# Product()N
.setPid(rs.!etInt(+))N
.setPid(rs.!etStrin!(2))N
.setPid(rs.!et'ouble(-))N
list.add()N
S
System.out.rintln(3%"ter& 3 =list.siXe())N
S
S
2
Hibernate !uys has !iven the "ollo#in! three %PI8s er"orm multile ro#
oerations. *hey are&
+. H?@ %PI
2. Criteria %PI
-. .ative s)l %PI
6hen #e develo $dbc alication to communicate #ith any database
server to remove the hard codin! #e use roerty 5les. %s art o" the
roerty 5les #e have rovided driver class, url, username, ass#ord
and )ueries. I" #e #ould like to communicate #ith other database
servers #e chan!e the values "rom roerty 5les.
Proerty 5les
H?@ )ueries as !iven as inut to hibernate SC6 it is the resonsibility o"
hibernate to convert H?@ )uery into corresondin! S?@ )ueries and send
into data base server.
2'BC %lication
'river class
url
username,
ass#ord
)uery8s
'B Server
2ava ro!ram usin! H?@
)uery
Hibernate SC6
>racle ,yS)le 'B2
2
Hibernate !uys has rovided so many direct classes. %s art o" this
dialect classes the code is rovided to convert H?@ )uery to
corresondin! s)l )ueries.
*he dialect classes are available in org3hibernate3dialect acka!e. *he
"ollo#in! are some o" the dialect classes. >racle dialect, ,yS)l dialect,
S%P dialect etc.
*he "ollo#in! are the "eatures o" s)l.
+. H?@ ?ueries "ully ob$ect oriented.
2. H?@ ?ueries suorts inheritance and oly morhism.
-. H?@ ?ueries are case sensitive.
I" #e #ant to #rite H?@ )ueries instead o" table names #e have to use
P>2> calss names.
Instead o" column names #e have to use roerty names H?@ )ueries
derived "rom s)l )ueries. *he "ollo#in! is H?@ )ueries derived "rom s)l
)ueries. *he "ollo#in! is H?@ and s)l )ueries to retrieve all the records
"rom em table.
S?@M select ; "rom emN
*able name
H?@M "rom in"o.inetsolv.(mloyee
P>2> calss name
'evelo a hibernate alication #hich uses H?@ )ueries to retrieve all
the records "rom em table.
;Procedure to use H01 in herbernate&
+. 0eresent H?@ )uery in the "orm o" )uery ob$ect.
2. Send the )uery ob$ect to hibernate so"t#are by callin! the list
method.
-. Hibernate SC6 returns an %rray@ist ob$ect render the %rray@ist
ob$ect and dislay the outut to client.
/. ?uery is an inter"ace #hich is available as ort o" or!.hibernate
acka!e. 6e can not create the ob$ect to )uery inter"ace. 6e can
create a re"erence variable and it holds imlementation class
ob$ect.
2
ublic class 0etrieve'ataR
ublic static void main(Strin! ar!sVW)R
CC Standard code
Session hsession P s".oenSession()N
?uery )uery P hsession.create?uery(h)l )uery)N
@ist l P )uery.list()N
%rray@ist emlist P (%rray@ist)lN
Iterator i P emlist.iterator()N
#hile(i.has.e7t())R
(mloyee e P ((mloyee)N.ne7t()N
System.out.rintln(e.!et(mloyee.o())N
System.out.rintln(e.!et(mloyee.ame())N
System.out.rintln(e.!et(mloyee%ddress())N
S
hsession.close()N
S
S
6hen #e call the list() method the "ollo#in! stes are carried out by list()
method.
+. H?@ )uery #ill be converted into corresondin! S?@ ?uery.
2. Hibernate SC6 send S?@ )uery to database server.
-. *he database server e7ecutes select )uery and return the 0esultSet
ob$ect to hibernate SC6.
/. Hibernate SC6 reresents every record in the "orm o" ob$ect and add
it to array list ob$ect.
1. @ist() method converts %rray@ist into suer class re"erence variable
list and it returns it #e have to !et %rray@ist ob$ect and dislay
records to client.
6hen #e tryin! to add any element to %rray@ist ob$ect it #ill be
converted into suer class ob$ect called as ob$ect. 6hile retrievin! data
"rom %rray@ist #e need to tyecast into aroriate ob$ect.
%s art H?@ )ueries #e can add #here conditions as #ell as order by
clause, !rou by clause.
;using where clause as part o H01&
2
S?@M select ; "rom em #here enoM2N
H?@M "rom in"o.inetsolv.(mloyee #here emloyeeM2N
;using positional parameters in H01&
*he "ollo#in! is an e7amle o" usin! ositional arameters in H?@.
S?@M select ; "rom roduct #here rice ML %nd riceUL
H?@M "rom roduct #here riceML %nd riceML
Ex&
Strin! )uery P 3"rom roduct #here riceML %nd riceUL4N
?uery h)l)uery P hsession.create)uery()uery)N
h)l)uery.Set'ouble(H,2HHH)N
h)l)uery.Set'ouble(+,1HHH)N
%rray@ist @ist P (%rray@ist)h)l)uery.list()N
In hibernate the H?@ )uery ositional arameter inde7 starts #ith H.
I" #e do not suly the values to all ositional arameters hibernate
dislay an e7cetion )uery e7cetion.
6e can use alias names as art o" H?@ )uery by usin! a key#ord as.
Ex&
Strin! )uery P 3"rom roduct as #here .riceML and .riceUL4N
6e can use order by as art o" H?@ )ueries.
Ex&
"rom roduct order by rice desc
;%etrieving specifc columns rom emplo(ee table&
*he "ollo#in! e7amle !et emloyee.o, emloyee.ame columns only
"rom the database server.
Strin! )uery P 3select emloyee.>,emloyee.ame "rom
in"o.inetsolv.(mloyee4N
?uery h)l )uery P hsession.Create?uery(?uery)N
%rraylist @ist P (%rraylist)h)l?uery.@ist()N
Iterator i P list.iterator()N
6hile(i.has.e7t())R
>b$ect oVW P (ob$ectVW)N
.e7t()N
2
CCcode to dislay the data "rom arrays usin! inde7.
"or(int $PoN$UH.lenthN$==)R
System.out.rintln(oV$W)N
S
S
*he "ollo#in! dia!ram sho#s ho# hibernate list() method as converted
the aroriate data in the array list.
>b$ect(2)
>b$ect(2)
Pro& 'evelo a hibernate alication to retrieve emloyee name column
only "rom em table.
Strin! ) P 3select emloyee name "rom emloyee4N
?uery )ue P hsession.Create?uery())N
%rray@ist list P (%rraylist)?uery.@ist()N
Iterator i P list.iterator()N
#hile(i.has.e7t())R
>b$ect o P i.ne7t()N
Inte!er ii P (Inte!er)oN
System.out.rintln(ii)NS
6hen #e have only one column in the select clause as art o" the array
list the data tye #ill be added.
Strin!
+
eone
2 et#o
Inte!er
Strin!
Inte!er
Strin!
+
eone
et#o
2
%
0
0
%
B
@
I
S
*
eone
et#o
ethree
eone
et#o
ethree
e"our
%
0
0
%
B
@
I
S
*
2
Strin!
Strin!
Strin!
rs
6e can use a!!re!ate "unctions in H?@ )ueries. *he "ollo#in! is an
e7amle usin! H?@ to 5nd number o" records available in roduct table.
Strin! ) P 3select count(;) "rom roduct as 4N
?uery )ue P hsession.Create?uery())N
%rray@ist list P (%rray@ist))ue.@ist()N
Iterator i P list.iterator()N
#hile(i.has.e7t())R
>b$ect o P i.ne7t()N
@on! l P (@on!)oN
System.out.rintln(o)N
S
6e can $oin multile tables and retrieve the records the "ollo#in! is an
e7amle o" $oin tables.
?uery H?@)uery
%rray list P (%rraylist)H?@)uery.@ist()N
Iterator &P list.iterator()N
#hile(i.has.e7t())R
>b$ect oVW P (ob$ectVW)i.ne7t()N
"or(int $PHN$UH.len!thN$==)R
(mloyee e P ((mloyee) oVHWN
Product P (Product) oV+WN
System.out.rintln(e.!et(mloyee .>() = 3\t4)N
System.out.rintln(e.!et(mloyee .ame() = 3\t4)N
System.out.rintln(.!etid() = 3\t4)N
System.out.rintln(.!et.ame() = 3\t4)N
e"our
2
S
S
By usin! H?@ #e can er"orm udatin!, deletion and insert records into a
database server. *o send the udate )uery #e use a method e7ecuted
udate().
*ransaction t7 P hsession.be!in*ransaction()N
Strin! )uery P 3udate in"o.inetsolv.(mloyee set emloyee
%ddressPZ 6here emloyee .o P L4N
?uery h)l?uery P hsession.create?uery(?uery)N
h)l?uery.setStrin!(H,47yX4)N
h)l?uery.setInte!er(+,+)N
int no P h)l?uery.e7ecuteudate()N
System.out.rintln(no)N
t7.commit()N
hsession.close()N
S
S
Note&
6hen #e er"orm udate, delete and insert oerations. 6e must
lace the code in a transaction.
H)l #ill not suort to insert record directly into table. i" the data is
already available in table #e can coy "rom one table to another table.
*ransaction t7 P hsession.be!in*ransaction()N
Strin! ?uery P 3insert into
(mloyee(emloyee.o,emloyee.ame) select id, name
"rom roduct4N
?uery h)l ?uery P hsession.create?uery(?uery)N
int no P h)l ?uery.e7ecuteudate()N
System.out.rintln(no)N
t7.commit()N
hsession.close()N
S
Named positional parameters&
2
6hen #e #rite the h)l ?ueries #e can use ositional arameters
the roblem #ith ositional arameters is i" somebody tryin! to read and
understand it takes lot o" time. Instead o" ositional arameters #e use
names. *his #ill imrove the readability o" the )ueries.
.amed ositional arameters #ill not imrove er"ormance searately.
*his is because by de"ault named ositional arameters also uses
reare statements. *he "ollo#in! is an e7amle o" named ositional
arameter.
Ex&
Arom roduct #here riceM&min value and riceU&ma7 value. *he
"ollo#in! is an e7amle o" usin! named ositional arameters.
Strin! ?uery P 3"rom roduct #here riceM&minvalue and
riceU&ma7value4N
?uery h)l ?uery P hsession.Create?uery(?uery)N
h)l ?uery.set'ouble(3minvalue4,2HHH)N
h)l ?uery.set'ouble(3ma7value4,DHHH)N
%rraylist list P (%rraylist)h)l?uery.@ist()N
In hibernate to retrieve the data "rom all the tables #e can use h)l )uery
like "rom $ava.lan!.ob$ect
Ex&
Strin! ?uery P 3"rom $ava.lan!.ob$ect4N
?uery h)l ?uery P hsession.Create?uery(?uery)N
%rraylist list P (%rraylist)h)l?uery.@ist()N
6hen the above list method is e7ecuted hibernate #ill send the )ueries
to read the data "rom all the tables. *he %rray list ob$ect contains the
P>2> class ob$ect "rom table as #ell as em tables.
$riteria )PI&
Criteria %PI is used to retrieve the records "rom the data base
server the advanta!e o" this %PI is #e are !oin! to reresent the )ueries
in the "orm o" ob$ects.
6e can not use Criteria %PI to insert the record, udate the record and
delete the record.
2
*he "ollo#in! is an e7amle o" usin! Criteria %PI to retrieve the records o"
roduct table.
Ex&
CCstandard hibernate code
Session hsession P s".oen Session()N
Criterial c P hsession.Create Criteria(Product.class)N
%rraylist list P (%rraylist)c.list()N
Iterator i P list.iterator()N
#hile(i.has.e7t())R
Product P (Product)N
ne7t()N
System.out.rintln(.!etPid())N
System.out.rintln(.!et.ame())N
System.out.rintln(.!etPrice())N
S
*o #ork #ith Criteria %PI #e must "ollo# the "ollo#in! t#o stes&
+. 0eresent the ?uery in the "orm o" Criteria ob$ect.
2. Send the Criteria to data base server by usin! a method list()N
Hibernate !uys has !iven rede5ned classes to add the restrictions. *hey
are available as art o" or!.hibernate.criteria acka!e some o" the
imortant classes in that are restrictions,order, roerty etc.
*he "ollo#in! is code to add restrictions to criteria.
Criteria c P hsession.create Criteria(Product.class)N
c.add(0estrictions.!e(3rice4,2HHHd)N
c.add(0estrictions.le(3rice4,/HHHd)N
*he 0estrictions class contains coule o" static "actory methods. *he
internal code o" these methods add() the #here conditions to the ?uery
as a develoer #e are resonsible to use these methods based on the
re)uirements.
*o sort the records based on Criteria %PI they have rovided rede5ned
classes like order. *his contains the methods like asc, desc.
Ex&
Criteria c P hsession.Create Criteria(roduct.class)N
2
c.add>rder(order.desc(3rice4))N
*o retrieve the seci5c columns "rom the data base table #e use
ro$ections class.
Ex&
Criteria c P hsession.Create Criteria(roduct.class)N
c.setPro$ection(Pro$ections.roerty(3name4))N
6hen #e run the above $ava ro!ram the %rray list ob$ect contains the
columns corresondin! data tye.
adding multiple projections&
Criteria c P hsession.Create Criteria(Product.class)N
Pro$ection@ist l P ro$ections.Pro$ection@ist()N
Pl.add(Pro$ections.roerty(3name4))N
Pl.add(Pro$ections.roerty(3id4))N
c.setPro$ection(l)N
Note&
Criteria %PI is not best sui table "or the real time ro$ects and to
develo comlicate ?ueries "or e7amle usin! the "unctions like di code,
nul+, nul2 etc.
Native '01 )PI&
*he main advanta!e o" .ative S?@ is #e can #rite data base
seci5c ?ueries as art o" hibernate. By usin! .ative S?@ %PI #e can
er"orm the oerations like insert ?uery, udate, delete, retrieve and call
the rocedures and etc.
*he "ollo#in! is an e7amle o" callin! the rocedure by usin! .ative S?@.
Ex&
*ransaction t7 P hsession.be!in*ransaction()N
S?@ ?uery ?uery P hsession.creteS?@?uery(3Rcall myrocS4)N
?uery.e7ecuteYadate()N
t7.commit()N
How do we use hibernate in web based applications4
How do we use hibernate in sturts4
2
+. Create a #eb based alication.
2. Coy all the hibernate related $ar 5les into ro$ect lib "older.
-. Coy hibernate con5!uration 5le, P>2> classes, hbm 5les and
hibernate con5!uration 5les into classes "older.
/. Create hbm 5le and servlet to cature data and store data.
5enerators&
In all the alications #hich #e develoed as o" ne# end user is suose
to enter the rimary key values.
It is not recommended to ask the end user to enter to enter the rimary
key values. It8s al#ays recommended to !enerate rimary key values by
the alication. *his resolves the roblem o" end user rememberin! the
rimary keys.
By usin! 2'BC #e have to #rite code to !enerate rimary key values. I"
#e use hibernate internally it contains a lo!ic to !enerate the rimary
key values.
)pproach*&
In this aroach #e 5nd the ma7imum values "rom corresondin! table
and increment by one and use it as rimary key value to 5nd the ne7t
rimary key value #e can use the "ollo#in! )uery.
Ex&
Select ma7(eno) = + "rom emN
*his lo!ic can be used in any data base server.
)pproach+&
>racle data base server suorts a "eature se)uences to !enerate the
rimary key values to create the se)uence #e use the "ollo#in! )uery.
Ex&
create se)uence emse)
min value +
ma7 value GGGGG
increment by +
start #ith +N
*o see all the available se)uences in the data base server. 6e use the
"ollo#in! )uery.
2
S?@M select ; "rom userOse)uencesN
)pproach,&
In mys)l there is a "eature auto increment. I" #e use it mys)l itsel" #ill
increment the rimary key values.
*o use auto increment at the time o" table is created #e must seci"y
auto increament.
Ex&
create table roduct(id int(1) rimary key autoOincreament,
name varchar(2H),
rice decimal(+H))N
*o insert the values #e use the "ollo#in! )uery.
Ex& insert into roduct(name,rice) values(<abc8,//1)N
auto increment #ill #rite in mys)l and 'B2. It does not #ork in oracle.
Hibernate has !iven set o" rede5ned classes to deal #ith rimary key
values. *hese classes are available in a acka!e. 3 or!.hibernate.id4
*he "ollo#in! are some o" the classes o" hibernate !enerators.
+. %ssi!ned
2. Se)uence !enerator
-. Increment !enerator
/. uuid !enerator
1. !uid !enerator etc.
Hibernate !uys has !iven an inter"ace identi5er !enerator this contain a
method !enerator.
%ll the above !enerator classes must rovide imlementation to an
inter"ace identi5er !enerator. %s art o" the !enerate method the lo!ic is
rovided to !enerate the rimary key value. *his method returns rimary
key value in the "orm o" serialiXable ob$ect.
%s art o" the hbm 5le there is a ta! !enerator. *his seci"y the
!enerator #hich has to be used by hibernate.
E6&
Identi5er !enerator
SerialiXable !enerate(QQQ)
2
U!enerator class P 3or!.hibernate.id .Se)uence 9enerator4CM
Hibernate !uys has rovided short names "or every !enerator. 6e can
use the short names on be hal" o" class names. *he "ollo#in! are some o"
the short names. %ssi!ned, se)uence, increment, native, hilo, uuid etc.
*he "ollo#in! is an e7amle o" usin! short names.
U!enerator class P 3se)uence4CM
Be"ore #e use a !enerator #e have to check the "ollo#in! t#o stes.
+. 6eather this !enerator can be used in the corresondin! data base
server or not.
2. 6e need to check #eather the !enerator suorts seci5c data
tye or not.
)ssigned generator&
6hen #e use assi!ned !enerator hibernate e7ect us to suly rimary
key value by de"ault #hen #e !enerator hbm and P>2> classes !enerator
is assi!ned #ith assi!ned value.
In the hbm 5le #e can use !enerator #ith hibernate class name or short
name.
Uid name P 3id4 tye P 3inte!er4M
Ucolumn name P 3id4CM
U!enerator class P 3or!.hibernate.id.%ssi!ned4CM
UCidM CC roduct.hbm.7ml
>0
Uid name P 3id4CM
Ucolumn name P 3id4CM
U!enerator class P 3assi!ned4CM
UCidM
In the hbm 5le i" #e does not suly the !enerator ta! by de"ault
hibernate consider assi!ned !enerator.
I" #e suly a #ron! class name or invalid !enerator class name
hibernate thro# an e7cetion could not instantiate id !enerator.
2
Increment generator&
6hen #e use this !enerator it #ill increment the rimary key value
by one based on e7istin! rimary key value. *his al!orithm internally
uses the e7istin! rimary key value.
6hen #e use this al!orithm it #ill use the "ollo#in! )uery to 5nd the
ma7imum rimary key value.
Ex& select ma7(id) "rom roduct
*he "ollo#in! is the con5!uration o" increment !enerator.
U!enerator class P 3or!.hibernate.id.Increment 9enerator4M
UC!eneratorM
U!enerator class P 3Increment4M
UC!eneratorM
Increment !enerator can !enerate the rimary key values "or short, lon!,
inte!er data tyes only.
6e can use increment !enerator in mys)l data base server also.
Identi( generator&
*his !enerator can be used only in mys)l data base server to use
this !enerator comulsory the table must be auto increment. *he
"ollo#in! is the con5!uration o" identi"y !enerator.
U!enerator class P 3or!.hibernate.id.dentity !enerator4CM
>0
U!enerator class P 3identity4CM
(se&uencehilo)&
'e& hilo& *his !enerator uses both se)uence as #ell as hilo value to
!enerator a rimary key value. *his is same as hilo !enerator. this uses
the se)uence instead o" table. the "ollo#in! is the con5!uration "or
se)uence hilo !enerator.
U!enerator class P 3se)hilo4M
Uaram name P 3se)uence4Midse)UCaramM
Uaram name P 3marOlo4M1UCaramM
UC!eneratorM
2
7uid8guid& *hese !enerators !enerate the rimary key value based on
the IP address o" the system and the start u time o" 2K, and convert it
into -2 bit he7adecimal number and store in data base server.
*o #ork #ith !uidCuuid !enerators the rimary key value data tye must
be var char #ith minimum siXe o" -2 bit. *he "ollo#in! is the
con5!uration o" !enerator.
U!enerator class P 3uuid4CM
Instead o" rede5ned !enerator #e can use our o#n !enerator also to
!et the rimary key values.
*o develo our o#n !enerator class it must rovide imlementation to
inter"ace identi5er !enerator. In this #e need to rovide the
imlementation to !enerator method.
Ex&
ublic class >ur>#n9enerator imlements Identi5er 9eneratorR
ublic serialiXable !enerator(SessionImlementor session, ob$ect
ob$ect)R
int eno P HN
0esultSet rs P
session.!etbatcher().PreareBatchStatement(3select ma7(eno)
"rom em4).e7ecute?uery()N
i"(rs.ne7t())R
eno P rs.!etInt(+)N
eno P eno = +N
S
return enoN
S
S
*o use this !enerator in hibernate #e have to con5!ure it in hbm 5le as
sho# belo#.
Ex& U!enerator class P 3in"o.inetsolv.ouro#n 9enerator4CM
6hen #e use hibernate in "orm based alications #e have rovided the
con5!ure method and build session "actory method as art o" service
method.
'ingle ton design pattern&
2
*he main urose o" sin!le ton desi!n attern is it make sure that
any #ork e7ecute only once or it make sure that the ob$ect is created to
a class only once.
*he "ollo#in! Cone class makes sure that it creates only one ob$ect "or
multile eole.
ublic class ConeR
rivate static Cone cN
StaticR
System.out.rintln(3creatin! Cone ob$ect only once4)N
c P ne# Cone()N
S
ublic static Cone create Cone ob$ect()R
return cN
S
Private Cone()R
System.out.rintln(3Cone ob$ect is created4)N
S
S
*o !et the Cone class ob$ect #e use a method created Cone ob$ect
ublic class ,y%()R
ublic static void main(Strin! ar!sVW)R
Cone c+ P Cone.create Cone ob$ect()N
Cone c2 P Cone.create Cone ob$ect()N
System.out.rintln(c+)N
System.out.rintln(c2)N
S
S
*he "ollo#in! is hibernate sin!le ton desi!n attern. *his class make sure
that session "actory is created only once.
ublic class Hibernate SessionAactorySin!le*onR
rivate Static SessionAactory s" P nullN
StaticR
Con5!uration c"! P ne# Con5!uration()N
c"!.con5!ure()N
2
s" P c"!.buildSessionAactory()N
S
ublic Static Session Aactory !etSessionAactory()R
return s!N
S
rivate HibernateSessionAactorySin!le*on()R
S
S
%s art o" a servelet #e !et the session ob$ect directly "rom sin!le ton
desi!n attern.
Ex& ublic class StoreProductServlet e7tends HttServletR
ublic void service(. . . . . . )R
Session hsession P HibernateSession "actory sin!le ton .
!etSession()N
. . . . . . . .
. . . . . .
. . . .
hsession.close()N
S
S
*he "ollo#in! is an e7amle hibernate temle desi!n attern. By usin!
this any body can er"orm the some oeration by usin! one line.
Ex&
ublic static void save(ob$ect o)R
Session hsession P Hibernate session "actory.!etSession()N
hsession.be!in*ransaction()N
hsession.Save(o)N
hsession.!et*ransaction().commit()N
Hibernate session "actory.close Session()N
S
S
'evelo a servlet to !et a all the records "rom roduct table and dislay
to the client.
Named 0ueries&
.amed ?ueries #ill imrove the er"ormance o" $ava alication.
2
6hen #e develo a #eb based alication to retrieve the records "rom
roduct table and dislay to the client by usin! H?@ ?ueries every time it
try to convert H?@ ?uery into corresondin! S?l ?uery. 6e can imrove
the er"ormance o" by usin! named ?ueries.
Procedure to use Named 0ueries&
+. Con5!ure .amed ?ueries as art o" hbm 5les.
Ex& UhibernateOmain!M
Uclass--- M
--------- M
UCclassM
U)uery name P 3!d4M"rom
in"o.inetsolv.roductUC)ueryM
UChibernateOmain!M CCroduct.hbm.7ml
2. Arom the $ava alication to use the .amed ?ueries use a
method.!et.amed?uery()
?uery )uery P hsession.!et.amed?uery(3!d4)N
%rray@ist al P (%rray@ist))uery.list()N
Iterator i P list.iterator()N
6hen #e are usin! .amed ?ueries #e can suly named ositional
arameters also.
Ex& U)uery name P 3!d4M"rom in"o.inetsolv.roduct #here name P&
nameUC)ueryM
.amed native S?@ #e can con5!ure native S?@ also as art o" hbm 5les.
*o con5!ure native s)l #e use a ta! Us)lO)ueryM
Ex&
UhibernateOmain!M
Uclass------ M
----------
UCclassM
Us)lO)ueryMname P 3hs)l4M select ; "rom roduct UCs)lO)ueryM
UChibernateOmain!M
*o call named s)l "rom $ava alication #e use a !et.amed ?uery this
returns )uery ob$ect. 6hen this send to data base server #e !et%rray@ist
ob$ect #ith ob$ect%rray as the values.
2
Ex& ?uery )uery P hsession.!et.amed?uery(3hs)l4)N
%rray@ist al P (%rray@ist))uery.list()N
Iterator i P al.iterator()N
#hile(i.has.e7t())R
ob$ect oVW P (ob$ectVW)i.ne7t()N
"or(int $PHN$UPH.len!thN$==)R
System.out.rintln(HV$W)N
S
S
Instead o" ob$ect %rray i" #e #ant to return a P>2> class ob$ect #e use
return ta!.in.hbm 5les as sho#n belo#.
Us)l-)uery name P 3hs)l4M
Ureturn class P 3in"o.inetslov.roduct4CM select ; "rom roduct
UCs)l-)ueryM
%s an alternative to connection method hibernate !uys has rovided do
#ork method.hibernate !uys has !iven inter"ace #ork. In this there is a
method e7ecute.
6e rovide any 2'BC code has art o" e7ecute method.
ublic class 2'BC6ork imlements #orksR
ublic void e7ecute(connection con)R
CallableStatemet cstmt P con.PreareCall(3Rcall myrocS4)N
cstmt.(7ecute()N
S
S
6hen #e #rite the business lo!ic in the rocedure they #ill imrove the
er"ormance. *he disadvanta!e o" this aroach. I" #e chan!e the data
base server the alication #ill not #ork as a $ava ro!rams #e
recommend to #rite the business lo!ic in $ava alication.
Hibernate is not the best solution #hen #e #rite the business lo!ic
in rocedure. It8s not recommended to use rocedures in the ro$ects
#hich uses hibernate. 6e are seen three aroaches o" callin!
rocedures "rom hibernate.
+. By !ettin! the connection "rom session ob$ect.
2. By usin! native S?@ alication.
-. By usin! do #ork method.
2
6hen #e use do #ork method hibernate internally uses callback
mechanism to call e7ecute method the advanta!e o" this is #e are not
oenin! the connection #e are not closin! the connection. % rocedure
can #rite multile records to achieve this #e have to use cursors in
rocedure.
Cursors are a temorary memory area. 6here the records #ill be stored
the cursor ob$ect #ill be created by oracle. 6hen ever select )uery is
e7ecuted in oracle they are t#o tyes o" cursors available. *hey are&
+. Imlicit cursors
2. (7licit cursors
*he "ollo#in! rocedure returns a cursorC0esultSet ob$ect create or
relace rocedure ,yProc( rs out sysOre"cursor)
%s
Be!in
oen rs "or select ; "rom roductN
end myrocN
C
Aollo#in! $ava alication to call the rocedure and dislay to the client.
ublic class 9et0ecordsR
ublic static void main(Strin! ar!sVW)R
CCstandard $dbc code
CallableStatement cstmt P con.PreareCall(3Rcall myroc(L)S4)N
cstmt.(7ecute()N
0esultSet rs P (0esultSet) cstmt.!et>b$ect(+)N
CCcode to dislay the records
S
S
Hibernate !uys are !ivin! a #ay to call rocedure #hich takes a
arameter re"cursor.
Con5!ure rocedure in hbm 5le as sho#n belo#.
UhibernateOmain!M
Uclass ----- M
----------
UCclassM
Us)lO)uery name P 3c4 callable P 3true4M
2
Ureturn class P 3in"o.inetsolv.roduct4MUCreturnM
Rcall myroc(L)S
UCs)lO)ueryM
UChibernateOmain!M
*o call the rocedure "rom $ava #e use named )ueries as sho#n belo#.
?uery )uery P hession.!et.amed?uery(3c4)N
%rraylist al P (%rraylist))uery.list()N
Iterator i P al .iterator()N
#hile(i.has.e7t())R
roduct P (roduct)i.ne7t()N
S
S
6e have to "ollo# limitations in hibernate to call the rocedure.
+. *he 5rst arameter rocedure must be out arameter and the data
tye must be re" cursor.
2. 6hen #e are con5!urin! the rocedure in #e must use on attribute
callable st.
6hen #e seci"y callable true hibernate re!ister. *he 5rst arameter as
out arameter #e must use native s)l to call the rocedure "rom
hibernate alication.
I" you #ant to search the records based on !iven roduct id you have to
suly a roduct id as arameter to rocedure. 6e can call that the
con5!ure in hbm 5le as sho#n belo#.
6e can develo a hibernate so"t#are to
communicate #ith multile data base servers "rom a sin!le ro$ect.
Procedure to use hibernate #ith multile data base servers "or the same
ro$ect. Create multile hibernate con5!uration 5les.
Ex&
hibernate.c"!.7ml
hibernate.mys)l.c"!.7ml
*o use multile data base servers in the ro$ect #e use multile
con5!uration 5les and multile session "actory ob$ects. In the ro$ects #e
do this #ork only once by usin! a sin!le ton desi!n attern only.
2
ublic class HibernateSessionAactoryR
rivate static SessionAactory os" P nullN
rivate static SessionAactory ms" P nullN
staticR
Con5!uration oc"! P ne# Con5!uration()N
oc"!.Con5!ure()N
Con5!uration mc"! P ne# Con5!uration()N
mc"!.Con5!ure(3hibernate.mys)l.c"!.7ml4)N
oc"!.buildSessionAactory()N
mc"!.buildSessionAactory()N
S
ublic static SessionAactory !et mys)lsessionAactoryR
return oc"!N S
ublic static SessionAactory !et mys)lsessionAactoryR
return mc"!N S
rivate HibernateSessionAactory()RS
In the $ava alication #e !et the re)uired Session Aactory ob$ect and
er"orm the oerations.
Ex& Sun ,icro System has released 2P% %PI to interact #ith data base
servers they are released this %PI as art o" 2(( standard %PI.
*he "ollo#in! is the classes and inter"aces as art o" 2P%.
$lasses Interaces
Persistence
Hibernate !uys rovided the imlementation to 2P% %PI.
Create a $ava ro$ect and add 2P% caabilities. *here are so many eole
#ho are rovidin! the imlementation same o" them or to link,
hibernate and oen 2P% and etc. #e can use any $ar 5les to develo 2P%
alication. 6hen #e add 2P% caabilities it has created an 7ml 5le
#hose name is ersistence.7ml in this #e have seci5ed ersistence unit
name.
9enerate an (ntity Beans (P>2> classes). 'evelo a $ava
alication to store the data into emloyee table.
ublic class Store(mR
ublic static void main(Strin! ar!sVW)R
2
(ntity,ana!erAactory em" P
Persistence.Create(ntity,ana!erAactory(32P%>0%C@(P4)N
(ntity,ana!er em P em".Create(ntity,ana!er()N
(ntity*ransaction t7 P em.!et*ransaction()N
t7.be!in()N
(m e P ne# (m()N
e.set(no(+)N
e.set(no(2)N
e.set(no(-)N
em.Persist(e)N
t7.commit()N
em.close()N
S
S
*he to link rovides the imlementation o" 2P% %PI to #ork #ith to link
#e are to do#nload the to link $ar 5les and set the class ath. 6hen #e
are develoin! a ro$ect at the desi!n hase #e try to develo t#o tyes
o" desi!n.
+. 'ata base desi!n
2. 2ava desi!n
%s art o" data base desi!n #e #ill decide the names o" the tables and
columns o" the tables and etc. %t the time o" develoin! the ro$ect
develoer #ill not create any tables. In most o" the ro$ects #e have to
cature multile address to an emloyee.
(no
.ame
%ddress&
Street city state
%'' another address
+
%m et
.aidu
HB'
HB'
S0
%P
%P
Store
2
*o imlement above re)uirement #e !ot the "ollo#in! desi!n.
Design *&
%s art o" desi!n #e are addin! t#o tables. (m table and address table
in the (m table (no is a rimary key. In the address table (no, %ddress
no are "ormin! the rimary key.
Design +&
In the desi!n2 the address table contain (no, addressno as rimary keys.
I" more than one column in valued in "ormin! a rimary key #e call it as
comosite rimary key. Hibernate #ill not !ive the best er"ormance i"
the table contains comosite rimary key. Hibernate !ive the best
er"ormance i" it8s havin! only one rimary key.
Design ,& In this desi!n #e have t#o tables. *hey are em and address.
In the address table #e #ill try to have a ne# column #hich acts as
rimary key.
(no .ame Street State
City
+ .aidu %m et %P HB'
(no(P:) .ame
salary
+ .aidu
(no %ddno Street State
City
+ + %m et %P HB'
(no(P:) .ame
salary
+ .aidu
+HHHHH
%id (no(P:) addno Street State
City
+ + + %Pet HB'
%P
2 2 + %Pet HB'
2
9enerally by usin! hibernate #e should be able to create the tables. but
accordin! to the ro$ect desi!n 5rst #e are creatin! tables "rom the
tables #e are creatin! P>2> classes. Creatin! the P>2> classes "rom the
table is called as hibernate reverse en!ineerin!.
*here are some situations #here #e need to develo hibernate
alications based on le!acy data base servers.
;;6hat are le!acy data base serversL
*he data base server #hich uses comosite rimary key8s is called as
le!acy data base servers. Procedure to develo hibernate alications
based on le!acy data base. Create the "ollo#in! the t#o tables.
!able *& create table em(eno number(1) rimary key,
.ame varchar2(2H), salary number(+H,2)N
!able +& create table address(eno number(1), addrno number(1),
State varchar2(2H), rimary key(eno, addrno))N
6hen #e !enerate hbm 5les and P>2> classes #e have observed that -
P>2> classes and t#o hbm 5les the P>2> classes are&
(m.$ava
%ddressId.$ava
%ddress.$ava
6e have not observed any chan!e in em P>2> class. *his is because
this table is havin! only one rimary key. 6e have observed that address
table is created. *#o P>2> classes&
+. Comosite rimary key class(%ddressId)
2. 0e!ular P>2> classes
*he comosite rimary key class contain t#o roerties this is because
t#o columns involvin! in "ormin! comosite rimary key.
2
ublic class %ddressIdR
Inte!er (noN
Inte!er addrnoN
CCsetters and !etters
S
*he "ollo#in! is address.$ava #hich uses comosite rimary key class as
a roerty.
ublic class %ddressR
%ddressId idN
Strin! streetN
Strin! cityN
Strin! stateN
CCrovide setters and !etters S
6e are !enerated t#o hbm 5les. *hey are&
+. (m.hbm.7ml
2. %ddress.hbm.7ml
6e have not observed any chan!es in (m.hbm.7ml 5les. 6e have
observed lot o" chan!es in address.hbm.7ml 5le #ith resect to
comosite rimary key.
UhibernateOmain!M
Uclass name P 3in"o.inetsolv.%ddress4 table P 3%ddress4M
Ucomosite-id name P 3id4 class P 3in"o.inetsolv.%ddressId4M
Ukey-roerty name 3(no4M
Ucolumn name P 3(no4CM
2
UCkey-roertyM
Ukey-roerty name P 3addno4M
Ucolumn name P 3%ddno4CM
UCkey-roertyMUCcomosite-idM
Uroerty name P 3street4CM
Uroerty name P 3city4CMUroerty name P 3state4CM
UCclassM
UhibernateOmain!M
*he "ollo#in! $ava alication to store the data into data base server
creatin! the em ob$.
+. %ddressId ob$
2. %ddress ob$
-. Call save method "or em.address
*o establish the relationshi bet#een tables #e do it based on the data
available in the tables. *hey are&
+. >ne to many
2. ,any to one
-. >ne to one
/. ,any to many
*o establish the relationshi bet#een tables #e do it based on the data
available in the tables.
"ne to man( relationship&
*o identi"y the relationshi bet#een the t#o tables #e use the data
based on the data available in the tables develo a hibernate alication
#hich uses one-to-many relationshi bC# em and address table. *he
"ollo#in! o" the t#o tables are created by em and address.
2
create table em((no number(1), .ame varchar2(2H), salary
number(+H,2))N
create table em add rimary key((no)N
create table address(%id number(1), (no number(1), %ddno number(1),
city varchar2(+H))N
alter table address add rimary key(%id)N
create table address(%id number(1) rimary key, (no number(1)
re"erences em((no)
#hen #e !enerate hbm 5les and P>2> classes #e !ot t#o hbm 5les and
P>2> classes. *he "ollo#in! is the P>2> class "rom em table.
ublic class emR alter table address add
Inte!er (mN "orei!n key((no) re"erences
Strin! nameN em((no)N
'ouble salaryN
Sent address P ne# HashSet(H)N
CCrovide settin! and !etters
S
*he "ollo#in! is the con5!uration o" the (m.hbm.7ml reresents the
many relationshi.
UhibernateOmain!M
Uclass name P 3in"o.inetsolv.(m4M
Uid name P 3(no4CM
Uroerty name P 3name4CM
Uroerty name P 3salary4CM
2
Uset name P 3address4 inverse P 3true4M
UkeyM
Ucolumn name P 3(.>4CM
UCkeyM
Uone-to-many class P 3in"o.inetsolv.%ddress4CM
UCsetM
UCclassM
UhibernateOmain!M
*he "ollo#in! is the P>2> class "or %ddress table.
ublic class %ddressR
Inte!er aidN
(m emN
Inte!er addnoN
Strin! streetN
Strin! cityN
Strin! stateN
CC rovide settress and !ettress
S
*he "ollo#in! hbm 5le "or address table.
UhibernateOmain!M
Uclass name P 3in"o.inetsolv.%ddress4M
Uid name P 3aid4CM
2
Umany-to-one name P 3(,P4 class P 3in"o.inetsolv.(m4M
Ucolumn name P 3(.>4CM
UCmany-to-oneM
Uroerty name P 3addrno4CM
Uroerty name P 3street4CM
Uroerty name P 3city4CM
Uroerty name P 3state4CM
UCclassM
UChibernateOmain!M
9enerally I'( reco!niXe the relationshi bet#een tables and !enerate
hbm 5les and P>2> classes. Hibernate understand the relationshi
bet#een the tables based on the ta!s #hich are available in hbm 5le. *o
reresent many relationshi in hibernate #e use collection ob$ects. *he
"ollo#in! are collection ob$ects o" hibernate.
@ist Set ,a Ba!
*hese collection ob$ects reresents many relationshis #e use hibernate
"rom the $ava side #e have to create the ob$ects store the data into
ob$ects and establish circular relationshi.
one
(no P null
.ame P null
Salary P
null
%ddress
(m
aid P null
a%ddrno P
null
city P null
state P
null
2
(m %ddress
Hashtable
*he "ollo#in! $ava alication to store the data into em as #ell as
address table.
ublic class storeR
ublic static void main(Strin! strVW)R
Session h P HibernateSessionAactory.!etSession()N
*ransaction t7 P h.be!in*ransaction()N
(m e P ne# (m()N
e.Set(no(+)N
e.Set.ame(3.aidu4)N
e.SetSalary(+H,HHH)N
%ddress a P ne# %ddress()N
a.Set%id(+)N
a.Set(m(e)N
a.Set%ddno(+)N
a.SetCity(3HB'4)N
a.SetState(3%P4)N
Set s P e.!et%ddress()N
s.add(a)N
h.Save(e)N
h.!et*ransaction.Commit()N
HibernateSessionAactory.CloseSession()N
6hen #e call save(e) hibernate can 5nd the relationshi bet#een the
tables and store the data into deendent on tables to do this #e must
seci"y t#o attributes inverse and cas code.
USet ----------- inverse P 3true4 cascade P 3all4CM
SiXe P
+
2
'evelo a $ava alication to retrieve the data "rom em table #ho em
no is 2 (#e #ould like to retrieve the corresondin! address details).
Hibernate checks t#o strate!ies to retrieve the record "rom data base
server.
+. @aXy loadin!------M %!!risive (ea!er) loadin!.
;;6hat is laXy loadin!L
6hen ever #e er"orm can oeration on one table and table has
relationshi #ith other tables and then #e called a load method it #ill
retrieve the data "rom that table only.
Hibernate retrieve the records "rom child table #hen even any oeration
is carried out o" any other table. By de"ault hibernate uses laXy
loadin!(true).
;;6hat is %!!ressive loadin!L
6hen ever #e call a load method on a arent table it #ill try to retrieve
record "orm child table also even thou!h user doesn8t access any
roerties. Ho# to make hibernate as a!!ressive #e have to con5!ure
laXy P 3"alse4 in hbm 5le o" arent table.
Uset ---------- inverse P 3true4 laXy P 3"alse4M
UCsetM
*he "ollo#in! is the e7amle o" retrieve the data "rom data base server
by usin! the load() method #hich is loadin! the relationshi.
ublic class 0etrieveR
ublic static void main(Strin! ar!sVW)R
Session s P HibernateSessionAactory.!etSession()N
(m e P ne# (m()N
e.!et(no()N
e.!et.ame()N
e.!etSalary()N
Set address P e.!et%ddress()N
System.out.rintln(address.SiXe())N
Iterator i P addresses.iterator()N
#hile(i.has.e7t())N
%ddress a P (%ddress)i.ne7t()N
System.out.rintln(a.!et%id())N
2
System.out.rintln(a.!et%ddno())N
System.out.rintln(a.!etCity())N
S
HibernateSessionAactory.!etSession()N
S
%s art o" P>2> classes and hbm 5le instead o" set #e can use only
hibernate tye @ist, ma, set, ba!.
Ex& 6e are usin! the list in the em table is sho#n belo#.
ublic class (mR
Inte!er enoN
Strin! nameN
'ouble salaryN
@ist address P ne# %rray@ist()N
S
*he "ollo#in! con5!uration o" (m.hbm.7ml
UhibernatOmain!M
Uclass name P 3in"o.inetsolv.em4M
Uid name P 3(no4CM
Uroerty name P 3name4CM
Uroerty name P 3salary4CM
Ulist name P 3address4 inverse P 3=ve4 cascade P 3all4M
Ukey column P 3(no4CM
Uinde7M
UCinde7M
Uone-to-many class P 3in"o.inetsolv.%ddress4CM
UClistM
UCclassM
UChibernatOmain!M
By de"ault hibernate uses inverse P 3"alse4 i" inverse P 3"alse4 hibernate
#ill not check the bi-directional relationshi bet#een tables. In this
scenario i" #e try to send multile insert )ueries and udate )uery. In
case o" inverse P 3true4 he check the bi-directional relationshi and store
the data by usin! insert )ueries.
2
Cascade attribute takes multile values. *hey are none, all, save-udate,
delete.
+. Cascade seci5es #hen ever #e er"orm any oeration on arent
table it er"orm the oeration on child table also. By de"ault in
hibernate cascade attribute value is name.
2. 6hen #e seci"y cascade P none #hen ever #e carry out any
oeration on arent table it does not carry out any oeration on
child table.
-. 6hen #e seci"y cascade P 3save-udate4 #hen ever #e er"orm
save oeration on arent table it #ill er"orm save oeration on the
child table also.
/. Cascade delete #hen #e seci"y cascade delete #hen ever #e
delete the record "rom arent table #e delete the record "rom child
table also. Instead o" seci"yin! every oeration #e seci"y cascade
P 3all4. 6e #ould like to maintain the customer and order details.
Customer table
>rder table
man(9to9one& 6e #ould like to maintain the tables "or multile
emloyees #e #ould like to have deartments and there are
deartments #ith out emloyees to achieve #e use many-to-one
relationshi.
(m
'et
one9to9one relationship&
Cid(k) Cname location
order(k) Cid("k) )uan rice
name
(no(k) name
'id("k)
'id(k)
name
2
6e #ould like to maintain one-to-one relationshi bet#een team
and catain tables. *he "ollo#in! are t#o takes #hich #e are usin! to
achieve this.
*eam
Catain
Note& 6hen #e create the above t#o tables and establish the
relationshis and !enerate hbm 5les and P>2> classes I'( as un-
necessarily created one-to-many relationshi this is because o" addin! a
"orei!n key relationshi bet#een catain and team table.
+. Create t#o tables team and catain #ith only rimary key do not
add the "orei!n in the be!innin! this is because i" #e had a "orei!n
key I'( #ill !enerate one-to-many relationshi.
2. 9enerate hbm 5les and P>2> classes.
-. 6e have to add one-to-one relationshi bet#een team and catain
by usin! roerties
Uhibernate-main!M
Uclass . . . . M
. . . . . . . . .
Uone-to-one name P 3catain4 class P 3in"o.inetsolv.catain4
cascade P 3all4M
UCone-to-oneM
UCclassM
UChibernate-main!M CCteam.hbm.7ml
*id(k) name
location
*id(k) (k)
Cname
2
Similar to team P>2> class and hbm 5le, develo catain $ava and
catain.hbm.7ml
;'evelo the hibernate alication to store data in to data base server.
ublic class Store*eam'etailsR
ublic static void main(Strin!VW ar!s)R
Session hsession P HibernateSessionAactory.!etSession()N
*ransaction t7 P hsession.be!in*ransactions()N
*eam t P ne# *eam()N
t.set*id(tid)N
t.set.ame(team.ame)N
t.set@ocation(location)N
Catain c P ne# Catain()N
c.set*id(tid)N
c.set.ame(catain)N
c.set*eam(t)N
t.setCation(c)N
hsession.save(c)N
t7.commit()N
HibenateSessionAactory.closeSession()N
S
S
man(9to9man(&
6e #ould like to imlement many-to-many relationshi bC# student
and course tables.
CCstudent CCcourse
CCstudent-course
*o seci"y the many-to-many relationshi bC# the tables #e have to
rovide the "ollo#in! con5!uration in hbm 5les.
Uset name P 3StudentCourses4 table P 3StudentOCourse4 CasCode P
3all4 inverse P 3true4M
Ukey column P 3Sid4CM
Umany-to-many column P 3cid4 class P 3in"o.inetsolv.course4CM
Sid(k) Sname Sid(k) Cid(k) Cid(k) Cname
2
UCsetM CCstudent.hbm.7ml
;;;*he "ollo#in! is the $ava code to store data in the data base server.
ublic class Store'ataR
ublic static void main(Strin! ar!sVW)R
Session hession P HibernateSessionAactory.!etSession()N
*ransaction t7 P hsession.be!in*ransaction()N
Course c P ne# Course()N
c.setCid(+)N
c.setCname(3$ava4)N
Student s+ P ne# Student()N
s+.setSid(+)N
s+.setSname(3ra$u4)N
Student s2 P ne# Student()N
s2.setSid(2)N
s2.setSname(3naveen4)N
setStudents P c.!etStudentCourse()N
Students.add(s+)N
Students.add(s2)N
c.setStudentCourses(students)N
hsession.save(c)N
t7.commit()N
HibenateSessionAactory.closeSession()N
S
S
*H%.:S