You are on page 1of 61

Hibernate Tutorial Step by Step -- Code Examples

by Satya Das Other Hibernate Examples with Code Other Hibernate Examples with Code Advantage of Hibernate over J !C Advantage of Hibernate over JDBC. Hibernate Setup with an web Appli"ation Hibernate Set p with an web Appli!ation #irst Hibernate Appli"ation Simple program to insert re!ord into database and fet!h the re!ords Hibernate mapping with atabase TA!$E Hibernate mapping with Database "AB#E.Here is the Example. Hibernate ata Type-Java ata Type - S%$ ata Type mapping "his t torial mapped the Hibernate Data "ype$Java Data "ype $ S%# Data "ype mapping. One to &any 'elation in Hibernate- (nidire"tional One to &any 'elation in Hibernate with Example. One to &any 'elation in Hibernate - !idire"tional One to &any 'elation in Hibernate Bidire!tional with Example. &any to &any 'elation in Hibernate &any to &any 'elation in Hibernate . H%$) The Hibernate %uery $anguage )from "lause*Asso"iations and +oins* Aggregate fun"tions*The order by "lause*The group by "lause*Sub,ueries"his t torial in!l des from !la se(Asso!iations and )oins( Aggregate f n!tions("he order by !la se("he gro p by !la se(S b* eries. Criteria %ueries Criteria % eries Criteria %ueries ) E,ual .e,/* 0ot E,ual.ne/* $ess than .le/* greater than .gt/*greater than or e,ual.ge/ and Ordering the results .order by/ E* al +e*,( -ot E* al+ne,( #ess than +le,( greater than +gt,(greater than or e* al+ge, and Ordering

the res lts +order by, Criteria %ueries) And O' "onditions "his se!tion will how the example of Criteria % eries. And O' !onditions Hibernate 1generator2 to generate id .primary 3ey/ in"rementally Sample program to show how Hibernate /generator0 to generate id +primary 1ey, in!rementally. (ser Thin3 Time 4ssue ) prevent "on"urrent update in Hibernate prevent !on! rrent pdate in Hibernate . How to perevent slate ob+e"t updatation in Hibernate 5 2erevent slate ob)e!t pdatation in Hibernate 3 6hat is version "he"3ing in Hibernate 5 4ersion !he!1ing in Hibernate Struts Spring Hibernate 4ntegration 6eb Appli"ation using Tom"at "his t torial g ide yo how yo !an integrate Str ts Spring Hibernate in a 5eb Appli!ation. "his is simple appli!ation where ser form +67, as Str ts and Servi!e as Spring and DAO is Hibernate. 6ser Details in the 6ser 8orm and save the details into DataBase. Other Hibernate Examples with Code Other Hibernate Examples with Code

Hibernate Tutorial Step by Step -- Code Examples


Advantage of Hibernate over JDBC

Advantage are 9, Hibernate is data base independent( same !ode will wor1 for all data bases li1e O'AC#E(&yS%# (S%#Server et!. 7n !ase of JDBC * ery m st be data base spe!ifi!. :, As Hibernate is set of Ob)e!ts ( yo don;t need to learn S%# lang age. <o !an treat "AB#E as a Ob)e!t . 7n !ase of JDBC yo need to learn S%#. =, Don;t need % ery t ning in !ase of Hibernate. 7f yo se Criteria % ires in Hibernate then hibernate a tomati!ally t ned yo r * ery and ret rn best res lt with performan!e. 7n !ase of JDBC yo need to t ne yo r * eries. >, <o will get benefit of Ca!he. Hibernate s pport two level of !a!he. 8irst level and :nd level. So yo !an store yo r data into Ca!he for better performan!e. 7n !ase of JDBC yo need to implement yo r )ava !a!he . ?, Hibernate s pports % ery !a!he and 7t will provide the statisti!s abo t yo r * ery and database stat s. JDBC -ot provides any statisti!s. @, Development fast in !ase of Hibernate be!a se yo don;t need to write * eries. A, -o need to !reate any !onne!tion pool in !ase of Hibernate. <o !an se !=pB. 7n !ase of JDBC yo need to write yo r own !onne!tion pool. C, 7n the xml file yo !an see all the relations between tables in !ase of Hibernate. Easy readability. D, <o !an load yo r ob)e!ts on start p sing laEyFfalse in !ase of Hibernate. JDBC Don;t have s !h s pport. 9B , Hibernate S pports a tomati! versioning of rows b t JDBC -ot.

Hibernate Tutorial Step by Step -- Code Examples


Hibernate Setup wit an web Appli!ation

8ollow the steps to set p Hibernate. Step 7- Create folders li3e below-

testApp | ----src // Java Source Code folder | -------------beans //Source Code folder | ----------------Offer.java //Source Code -------------servlet //Source Code folder | ----------------DBStartUpServlet.java //Source Code -------------dao //Source Code folder | ----------------HibernateUtil.java //Source Code ----confi // confi folder !"ere all t"e confi uration files present | -------------"ibernate.cf .#$l //Hibernate Confi file -------------Offer."b$.#$l// "ibernate $appin !it" Offer %AB&' -------------lo (j.properties// lo (j settin ----)'B-*+, //!it"in folder | ---------!eb.#$l //file ---------classes //folder ---------lib //!it"in folder | -------------"ibernate-.jar //jar file -------------antlr-../.0rc1.jar //jar file -------------as$.jar //jar file -------------as$-attrs.jar //jar file -------------c-p2-2.3.2.jar //jar file for connection pool -------------classes1..jar //if 4ou use O5AC&' DA%ABAS' jar file -------------$4s6l-connector-java-7.2.(-bin.jar //if 4ou use 84S9& DA%ABAS' jar file -------------co$$ons-lo in .jar //jar file -------------co$$ons-validator.jar //jar file -------------do$(j-1.0.1.jar //jar file -------------jta.jar //jar file -------------lo (j-1...11.jar //jar file -------------nls:c"arset1..jar //jar file

Step 8- Add !Start(pServlet Entry into the web-xml file "his servlet is only for load !onfig ration files related to Hibernate and !reate Session 8a!tory on start p . Create Session #a"tory is very Expensive

Create Session 8a!tory is very Expensive so we added one servlet to !reate on server start p 4nitiali9e Conne"tion pool on startup 7nitialiEe Conne!tion pool on start p sing !=pB. 4nitiali9e log:+ "onfiguration 7nitialiEe log>) !onfig ration on start p.
;<#$l version=>1.2> encodin =>*SO-??73-1><@ ;ADOC%BC' !eb-app CUB&*C >-//Sun 8icros4ste$sD *nc.//D%D )eb Application ..-//'+> >"ttpE//java.sun.co$/dtd/!eb-app:.:-.dtd>@ ;!eb-app@ ;displa4-na$e@Hibernate;/displa4-na$e@ ;description@ Hibernate Setup ;/description@ ;servlet@ ;servlet-na$e@ DBStartUpServlet ;/servlet-na$e@ ;servlet-class@ servlet.DBStartUpServlet ;/servlet-class@ ;load-on-startup@1;/load-on-startup@ ;/servlet@ ;/!eb-app@

Step ;- !Start(pServlet Code


package servlet; public class DBStartUpServlet extends HttpServlet { /** Initialising the Logger */ protected static inal Logger logger!Logger"getLogger#DBStartUpServlet"class$; public void init#Servlet%on ig con ig$ thro&s Servlet'xception { S(ste)"out"println#*+n**** Initiali,ing Hibernate Init Servlet ********** +n*$; super"init#con ig$;

//-his is or local properties" String c gDir ! *D.++test/pp++con ig*; logger"in o#*con ig dir.*0c gDir$; initLog1ro#c gDir$; tr({ HibernateUtil"appHo)e ! c gDir; HibernateUtil"init2onitor#$;

3catch#'xception e${ e"printStack-race#$; 3

3 /** Handles the re4uests ro) http client" * 5para) re4uest servlet re4uest * 5para) response servlet response */ protected void service#HttpServlet6e4uest re4uest7HttpServlet6esponse response$ thro&s Servlet'xception7 8ava"io"I9'xception { 3

private void initLog1ro#String path${ tr({ 1ropert(%on igurator"con igure#path0:ile"separator%har0*log;8"properties*$; 3catch#'xception ex${ S(ste)"out"println#*Log;< can not be initiali,ed*$; logger"in o#*Log;< can not be initiali,ed*$;

3 3

Step :- Hibernate(til-+ava "ode


package dao; public class HibernateUtil { public static String appHo)e ! *=o*; private static Session:actor( session:actor(; private static inal -hreadLocal threadSession ! ne& -hreadLocal#$; private static inal -hreadLocal thread-ransaction ! ne& -hreadLocal#$; // %reate the initial Session:actor( con iguration iles public static void con igure#${ tr( { String path>properties ! ro) the de ault

appHo)e0:ile"separator%har0*hibernate"c g"x)l*; %on iguration con iguration ! ne& %on iguration#$; con iguration"add:ile#path>properties$; session:actor( !con iguration"con igure#$"buildSession:actor(#$; 3 catch #-hro&able ex$ { thro& ne& 'xceptionInInitiali,er'rror#ex$; 3 3 public static Session:actor( getSession:actor(#$ { i #session:actor(!!null$ con igure#$; return session:actor(; 3 public static Session getSession#${ Session s ! #Session$ threadSession"get#$; // logger"debug#*session*0s$; i #s !! null$ { s ! getSession:actor(#$"openSession#$; threadSession"set#s$; // logger"debug#*session ? @*0s$; 3 return s; 3 3

Step <- hibernate-"fg-xml for hibernate "onfiguration .within "onfig folder/


;<#$l version=F1.2F encodin =Futf-?F<@ ;ltGADOC%BC' "ibernate-confi uration CUB&*C >-//Hibernate/Hibernate Confi uration D%D -.2//'+> >"ttpE//"ibernate.sourcefor e.net/"ibernate-confi uration--.2.dtd>@ ;"ibernate-confi uration@ ;session-factor4@ ;A-- Database connection settin s --@ ;propert4 na$e=>connection.driver:class>@co$.$4s6l.jdbc.Driver;/propert4@ ;propert4 na$e=>connection.url>@jdbcE$4s6lE//local"ostE--20/tec"fa6db;/propert4 @ ;propert4 na$e=>connection.userna$e>@tec"fa6;/propert4@ ;propert4 na$e=>connection.pass!ord>@tec"fa6;/propert4@

;A-- JDBC connection pool Huse t"e built-inI --@ ;propert4 na$e=>"ibernate.c-p2.$in:siJe>@1;/propert4@ ;propert4 na$e=>"ibernate.c-p2.$a#:siJe>@(;/propert4@ ;propert4 na$e=>"ibernate.c-p2.ti$eout>@1?22;/propert4@ ;propert4 na$e=>"ibernate.c-p2.$a#:state$ents>@72;/propert4@ ;A-- 84S9& dialect//different for different Database --@ ;propert4 na$e=>dialect>@or ."ibernate.dialect.84S9&Dialect;/propert4@ ;A-- 'nable HibernateFs auto$atic session conte#t $ana e$ent --@ ;propert4 na$e=>current:session:conte#t:class>@t"read;/propert4@ ;A-- Disable t"e second-level cac"e --@ ;propert4 na$e=>cac"e.provider:class>@or ."ibernate.cac"e.+oCac"eCrovider;/pro pert4@ ;A-- 'c"o all e#ecuted S9& to stdout --@ ;propert4 na$e=>s"o!:s6l>@true;/propert4@ ;propert4 na$e=>"b$.ddl.auto>@update;/propert4@ ;$appin resource=>Offer."b$.#$l>/@ ;/session-factor4@ ;/"ibernate-confi uration@

Step =- Offer-+ava bean "lass-.within beans folder/


package beans; public class 9 er { private long o erId; private String o er=a)e; /** * 5return 6eturns the o erId" */ public long get9 erId#$ { return o erId; 3 /** * 5para) o erId -he o erId to set" */ private void set9 erId#long o erId$ { this"o erId ! o erId; 3 /** * 5return 6eturns the o er=a)e" */ public String get9 er=a)e#$ { return o er=a)e; 3 /** * 5para) o er=a)e -he o er=a)e to set"

*/ public void set9 er=a)e#String o this"o er=a)e ! o er=a)e; 3 3

er=a)e$ {

Step >- Offer-+ava and O##E' TA!$E mapping in Offer-hbm-xml


;<#$l version=>1.2><@ ;ADOC%BC' "ibernate-$appin CUB&*C >-//Hibernate/Hibernate 8appin D%D -.2//'+> >"ttpE//"ibernate.sourcefor e.net/"ibernate-$appin --.2.dtd>@ ;"ibernate-$appin @ ;class na$e=>beans.Offer> table=>O,,'5>@ ;id na$e=>offer*d> colu$n=>offer:id> t4pe=>lon >@ ; enerator class=>incre$ent>/@ // %"is enerates t"e pri$ar4 Ke4 ;/id@ ;propert4 na$e=>offer+a$e> colu$n=>offer:na$e>/@ ;/class@ ;/"ibernate-$appin @

Step ?- O##E' TA!$E in your database


create table O,,'5 H offer:id nu$berG offer:na$e varc"ar IG

"hen start the server. <o r Session8a!tory is ready to serve. <o !an !all Hibernate6til.getSession+, to get session ob)e!t and do yo r !oding.

Hibernate Tutorial Step by Step -- Code Examples


"irst Hibernate Appli!ation

"his se!tion des!ribe a simple program to insert re!ord into database and fet!h the re!ords 8ollow the setps Step 7- "reate a table name E&@$OAEE in your database
// for 84S9& create table '8C&OB'' H id bi intH.2I D

na$e varc"ar IG // ,O5 O5AC&' create table '8C&OB'' H id nu$berG na$e varc"ar IG

Step 8- Create Emp-+ava bean "lassHibernate ses the 2lain Old Java Ob)e!ts +2OJOs, !lasses to map to the database table +Emp.)ava to E&2#O<EE "AB#E,. 5e !an !onfig re the variables to map to the database !ol mn.
public class ')p { private long id; private String na)e; public long getId#$ { return id; 3 private void setId#long id$ { this"id ! id; 3 public String get=a)e#$ { return na)e; 3 public void set=a)e#String na)e$ { this"na)e ! na)e; 3 3

Step ;- Emp-hbm-xml - This mapps E&@$OAEE TA!$E and Emp-+ava


;<#$l version=>1.2><@ ;ADOC%BC' "ibernate-$appin CUB&*C >-//Hibernate/Hibernate 8appin D%D -.2//'+> >"ttpE//"ibernate.sourcefor e.net/"ibernate-$appin --.2.dtd>@ ;"ibernate-$appin @ ;class na$e=>'$p> table=>'8C&OB''>@ ;id na$e=>id> colu$n=>id> t4pe=>lon >@ ; enerator class=>incre$ent>/@ // %"is enerates t"e pri$ar4 Ke4

;/id@ ;propert4 na$e=>na$e> colu$n=>na$e>/@ ;/class@ ;/"ibernate-$appin @

Step :- add Emp-hbm-xml into hibernate-"fg-xml Hibernate provided !onne!tion pooling sning !=pB and transa!tion management . Hibernate ses the hibernate.!fg.xml to !reate the !onne!tion pool and set p re* ired environment
;<#$l version=F1.2F encodin =Futf-?F<@ ;ltGADOC%BC' "ibernate-confi uration CUB&*C >-//Hibernate/Hibernate Confi uration D%D -.2//'+> >"ttpE//"ibernate.sourcefor e.net/"ibernate-confi uration--.2.dtd>@ ;"ibernate-confi uration@ ;session-factor4@ ;A-- Database connection settin s --@ ;propert4 na$e=>connection.driver:class>@co$.$4s6l.jdbc.Driver;/propert4@ ;propert4 na$e=>connection.url>@jdbcE$4s6lE//local"ostE--20/tec"fa6db;/propert4 @ ;propert4 na$e=>connection.userna$e>@tec"fa6;/propert4@ ;propert4 na$e=>connection.pass!ord>@tec"fa6;/propert4@ ;A-- JDBC connection pool Huse t"e built-inI --@ ;propert4 na$e=>"ibernate.c-p2.$in:siJe>@1;/propert4@ ;propert4 na$e=>"ibernate.c-p2.$a#:siJe>@(;/propert4@ ;propert4 na$e=>"ibernate.c-p2.ti$eout>@1?22;/propert4@ ;propert4 na$e=>"ibernate.c-p2.$a#:state$ents>@72;/propert4@ ;A-- 84S9& dialect//different for different Database --@ ;propert4 na$e=>dialect>@or ."ibernate.dialect.84S9&Dialect;/propert4@ ;A-- 'nable HibernateFs auto$atic session conte#t $ana e$ent --@ ;propert4 na$e=>current:session:conte#t:class>@t"read;/propert4@ ;A-- Disable t"e second-level cac"e --@ ;propert4 na$e=>cac"e.provider:class>@or ."ibernate.cac"e.+oCac"eCrovider;/pro pert4@ ;A-- 'c"o all e#ecuted S9& to stdout --@ ;propert4 na$e=>s"o!:s6l>@true;/propert4@ ;propert4 na$e=>"b$.ddl.auto>@update;/propert4@ ;$appin resource=>'$p."b$.#$l>/@ ;/session-factor4@

;/"ibernate-confi uration@

Step <- Here is the "ode for Save and #et"h dataHibernate Session is the main r ntime interfa!e for Hibernate whi!h is sed for DataBase operataion. Session has the method li1e save +, ( pdate +, ( !rete% ery+, for Data Base operation. <o !an get session sing Session8a!tory.openSession+, method. Session8a!tory allows appli!ation to !reate the Hibernate Sesssion by reading the !onfig ration from hibernate.!fg.xml file. "hen the save +, method on session ob)e!t is sed to save the !onta!t information to the database.
public class -est'xa)ple { public static void )ain#StringAB args$ { Session session ! null; tr({ // -his step &ill read hibernate"c g"x)l Session:actor( session:actor( ! ne& %on iguration#$"con igure#$"buildSession:actor(#$; session !session:actor("openSession#$; S(ste)"out"println#*Inserting 6ecords*$; ')p e)p? ! ne& ')p#$; e)p?"set=a)e#*=ick*$; session"save#e)p?$; ')p e)pC ! ne& ')p#$; e)pC"set=a)e#*Das*$; session"save#e)pC$; session" lush#$; // insert data into databse S(ste)"out"println#*Save DoneD inish database insert*$; // =o& etch the ')plo(ee data List e)pList ! session"createEuer(#* ro) ')p*$"list#$; //e)pList contains the list o ')plo(ee or#int i!F;i ')p e)p ! #')p$e)pList"get#i$; S(ste)"out"println#e)p"get=a)e#$$; 3 // 9ut put is . =ick Das 3catch#'xception e${ 3 inall({ session"close#$; 3 3 3

Hibernate Tutorial Step by Step -- Code Examples


Hibernate mapping wit Database TAB#E

8ollow the steps to mapp with Database "AB#E. Step 7- "reate a table name O##E' in your database
create table O,,'5 H offer:id nu$berG offer:na$e varc"ar IG

Step 8- Create Offer-+ava bean "lasspackage beans; public class 9 er { private long o erId; private String o er=a)e; /** * 5return 6eturns the o erId" */ public long get9 erId#$ { return o erId; 3 /** * 5para) o erId -he o erId to set" */ private void set9 erId#long o erId$ { this"o erId ! o erId; 3 /** * 5return 6eturns the o er=a)e" */ public String get9 er=a)e#$ { return o er=a)e; 3 /** * 5para) o er=a)e -he o er=a)e to set" */ public void set9 er=a)e#String o er=a)e$ { this"o er=a)e ! o er=a)e; 3 3

Step ;- Offer-hbm-xml - This mapps O##E' TA!$E and Offer-+ava


;<#$l version=>1.2><@ ;ADOC%BC' "ibernate-$appin CUB&*C

>-//Hibernate/Hibernate 8appin D%D -.2//'+> >"ttpE//"ibernate.sourcefor e.net/"ibernate-$appin --.2.dtd>@ ;"ibernate-$appin @ ;class na$e=>beans.Offer> table=>O,,'5>@ ;id na$e=>offer*d> colu$n=>offer:id> t4pe=>lon >@ ; enerator class=>incre$ent>/@ // %"is enerates t"e pri$ar4 Ke4 ;/id@ ;propert4 na$e=>offer+a$e> colu$n=>offer:na$e>/@ ;/class@ ;/"ibernate-$appin @

Step :- add Offer-hbm-xml into hibernate-"fg-xml


;<#$l version=F1.2F encodin =Futf-?F<@ ;ltGADOC%BC' "ibernate-confi uration CUB&*C >-//Hibernate/Hibernate Confi uration D%D -.2//'+> >"ttpE//"ibernate.sourcefor e.net/"ibernate-confi uration--.2.dtd>@ ;"ibernate-confi uration@ ;session-factor4@ ;A-- Database connection settin s --@ ;propert4 na$e=>connection.driver:class>@co$.$4s6l.jdbc.Driver;/propert4@ ;propert4 na$e=>connection.url>@jdbcE$4s6lE//local"ostE--20/tec"fa6db;/propert4 @ ;propert4 na$e=>connection.userna$e>@tec"fa6;/propert4@ ;propert4 na$e=>connection.pass!ord>@tec"fa6;/propert4@ ;A-- JDBC connection pool Huse t"e built-inI --@ ;propert4 na$e=>"ibernate.c-p2.$in:siJe>@1;/propert4@ ;propert4 na$e=>"ibernate.c-p2.$a#:siJe>@(;/propert4@ ;propert4 na$e=>"ibernate.c-p2.ti$eout>@1?22;/propert4@ ;propert4 na$e=>"ibernate.c-p2.$a#:state$ents>@72;/propert4@ ;A-- 84S9& dialect//different for different Database --@ ;propert4 na$e=>dialect>@or ."ibernate.dialect.84S9&Dialect;/propert4@ ;A-- 'nable HibernateFs auto$atic session conte#t $ana e$ent --@ ;propert4 na$e=>current:session:conte#t:class>@t"read;/propert4@ ;A-- Disable t"e second-level cac"e --@ ;propert4 na$e=>cac"e.provider:class>@or ."ibernate.cac"e.+oCac"eCrovider;/pro pert4@

;A-- 'c"o all e#ecuted S9& to stdout --@ ;propert4 na$e=>s"o!:s6l>@true;/propert4@ ;propert4 na$e=>"b$.ddl.auto>@update;/propert4@ ;$appin resource=>Offer."b$.#$l>/@ ;/session-factor4@ ;/"ibernate-confi uration@

Hibernate Tutorial Step by Step -- Code Examples


Hibernate Data Type-Java Data Type - S$# Data Type mapping
<ava -(pe Integer7 int7 long short char 8ava")ath"BigDeci)al 6 loat7 double 8ava"lang"Boolean7 boolean Hibernate -(pe integer7 long7 short character big>deci)al SEL -(pe nu)ber char =U2'6I%7 =U2B'

loat7 double boolean

loat7 double boolean7 int

8ava"lang"string arC Ger( long strings 8ava"util"Date 2'S-/21 8ava"util"%alendar ' 8ava"util"Locale rC 8ava"util"-i)eIone

string

varchar7 varch

text date7 ti)e7 ti)esta)p

%L9B7 -'HD/-'7 -I2'7 -I

calendar7 calendar>date

-I2'S-/217 D/-

locale

varchar7varcha

ti)e,one

varchar7 varch

arC 8ava"util %urrenc( arC 8ava"s4l"%lob 8ava"s4l"Blob <ava ob8ect byte arra( 8ava"lang"Class arC %urrenc( varchar7 varch

clob blob seriali,able binar( class

%L9B BL9B binar( binar( ield ield

varchar7 varch

Hibernate Tutorial Step by Step -- Code Examples


%ne to &any ' (ni-Dire!tional )elation in Hibernate

"here are two table 5'7"E' and S"O'<. One writer !an write m ltiple stories. So the relation is one$to$many ni$dire!tional. Step 7- "reate a table name 6'4TE' and STO'A in your database
create table )5*%'5 H *D nu$berD //C5*8A5B L'B +A8' varc"ar IG create table S%O5B H *D nu$berD *+,O varc"arD CA5'+%:*D nu$ber // fori n Ke4 - relate to *D Coul$n of )5*%'5. IG

Step 8- &apping writer-hbm-xml- 6hi"h maps to 6'4TE' TA!$E;<#$l version=>1.2><@ ;ADOC%BC' "ibernate-$appin CUB&*C >-//Hibernate/Hibernate 8appin D%D -.2//'+> >"ttpE//"ibernate.sourcefor e.net/"ibernate-$appin --.2.dtd>@ ;"ibernate-$appin @

;class na$e=>)riter> table=>)5*%'5>@ ;id na$e=>id> colu$n=>*D> t4pe=>int> unsaved-value=>2>@ ; enerator class=>incre$ent>/@ ;/id@ ;list na$e=>stories> cascade=>all>@ ;Ke4 colu$n=>parent:id>/@ ;one-to-$an4 class=>Stor4>/@ ;/list@ ;propert4 na$e=>na$e> colu$n=>+A8'> t4pe=>strin >/@ ;/class@ ;/"ibernate-$appin @

Step ;- &apping story-hbm-xml- 6hi"h maps to STO'A TA!$E;<#$l version=>1.2><@ ;ADOC%BC' "ibernate-$appin CUB&*C >-//Hibernate/Hibernate 8appin D%D -.2//'+> >"ttpE//"ibernate.sourcefor e.net/"ibernate-$appin --.2.dtd>@ ;"ibernate-$appin @ ;class na$e=>Stor4> table=>stor4>@ ;id na$e=>id> colu$n=>*D> t4pe=>int> unsaved-value=>2>@ ; enerator class=>incre$ent>/@ ;/id@ ;propert4 na$e=>info> colu$n=>*+,O> t4pe=>strin >/@ ;/class@ ;/"ibernate-$appin @

Step :- Create 6riter-+ava bean "lasspublic class Jriter { private int id; private String na)e; private List stories; public void setId#int i$ { id ! i; 3 public int getId#$ { return id; 3 public void set=a)e#String n$ { na)e ! n; 3 public String get=a)e#$ {

return na)e; 3 public void setStories#List l$ { stories ! l; 3 public List getStories#$ { return stories; 3 3

Step <- Create Story-+ava bean "lasspublic class Stor( { private int id; private String in o; public Stor(#${ 3 public Stor(#String in o$ { this"in o ! in o; 3 public void setId#int i$ { id ! i; 3 public int getId#$ { return id; 3 public void setIn o#String n$ { in o ! n; 3 public String getIn o#$ { return in o; 3 3

Step =- add writer-hbm-xml and story-hbm-xml into hibernate-"fg-xml


;<#$l version=F1.2F encodin =Futf-?F<@ ;ltGADOC%BC' "ibernate-confi uration CUB&*C >-//Hibernate/Hibernate Confi uration D%D -.2//'+> >"ttpE//"ibernate.sourcefor e.net/"ibernate-confi uration--.2.dtd>@ ;"ibernate-confi uration@ ;session-factor4@ ;A-- Database connection settin s --@ ;propert4

na$e=>connection.driver:class>@co$.$4s6l.jdbc.Driver;/propert4@ ;propert4 na$e=>connection.url>@jdbcE$4s6lE//local"ostE--20/tec"fa6db;/propert4 @ ;propert4 na$e=>connection.userna$e>@tec"fa6;/propert4@ ;propert4 na$e=>connection.pass!ord>@tec"fa6;/propert4@ ;A-- JDBC connection pool Huse t"e built-inI --@ ;propert4 na$e=>"ibernate.c-p2.$in:siJe>@1;/propert4@ ;propert4 na$e=>"ibernate.c-p2.$a#:siJe>@(;/propert4@ ;propert4 na$e=>"ibernate.c-p2.ti$eout>@1?22;/propert4@ ;propert4 na$e=>"ibernate.c-p2.$a#:state$ents>@72;/propert4@ ;A-- 84S9& dialect//different for different Database --@ ;propert4 na$e=>dialect>@or ."ibernate.dialect.84S9&Dialect;/propert4@ ;A-- 'nable HibernateFs auto$atic session conte#t $ana e$ent --@ ;propert4 na$e=>current:session:conte#t:class>@t"read;/propert4@ ;A-- Disable t"e second-level cac"e --@ ;propert4 na$e=>cac"e.provider:class>@or ."ibernate.cac"e.+oCac"eCrovider;/pro pert4@ ;A-- 'c"o all e#ecuted S9& to stdout --@ ;propert4 na$e=>s"o!:s6l>@true;/propert4@ ;propert4 na$e=>"b$.ddl.auto>@update;/propert4@ ;$appin resource=>stor4."b$.#$l>/@ ;$appin resource=>!riter."b$.#$l>/@ ;/session-factor4@ ;/"ibernate-confi uration@

Here is the "ode ) how to save


Save 'xa)ple "" Jriter &r ! ne& Jriter#$; &r"set=a)e#*Das*$; /rra(List list ! ne& /rra(List#$; list"add#ne& Stor(#*Stor( =a)e ?*$$; list"add#ne& Stor(#*Stor( =a)e C*$$; &r"setStories#list$; -ransaction transaction ! null; tr( { transaction ! session"begin-ransaction#$; session"save#&r$; transaction"co))it#$; 3 catch #'xception e$ { i #transaction K! null$ {

transaction"rollback#$; thro& e; 3 3 inall( { session"close#$; 3

Hibernate Tutorial Step by Step -- Code Examples


%ne to &any Bi-Dire!tional )elation in Hibernate

"here are two table 5'7"E' and S"O'<. One writer !an write m ltiple stories. So the relation is one$to$many . "his t torial des!ribe the bi$dire!tional relation. 8rom 5'7"E' ob)e!t yo !an get list of Stories and from story ob)e!t yo !an get writer ob)e!t. Step 7- "reate a table name 6'4TE' and STO'A in your database
create table )5*%'5 H *D nu$berD //C5*8A5B L'B +A8' varc"ar IG create table S%O5B H *D nu$berD *+,O varc"arD CA5'+%:*D nu$ber // fori n Ke4 - relate to *D Coul$n of )5*%'5. IG

Step 8- &apping writer-hbm-xml- 6hi"h maps to 6'4TE' TA!$E;<#$l version=>1.2><@ ;ADOC%BC' "ibernate-$appin CUB&*C >-//Hibernate/Hibernate 8appin D%D -.2//'+> >"ttpE//"ibernate.sourcefor e.net/"ibernate-$appin --.2.dtd>@ ;"ibernate-$appin @ ;class na$e=>)riter> table=>)5*%'5>@ ;id na$e=>id> colu$n=>*D> t4pe=>int> unsaved-value=>2>@ ; enerator class=>incre$ent>/@ ;/id@ ;list na$e=>stories> cascade=>all>@ ;Ke4 colu$n=>parent:id>/@

;one-to-$an4 class=>Stor4>/@ ;/list@ ;propert4 na$e=>na$e> colu$n=>+A8'> t4pe=>strin >/@ ;/class@ ;/"ibernate-$appin @

Step ;- &apping story-hbm-xml- 6hi"h maps to STO'A TA!$E;<#$l version=>1.2><@ ;ADOC%BC' "ibernate-$appin CUB&*C >-//Hibernate/Hibernate 8appin D%D -.2//'+> >"ttpE//"ibernate.sourcefor e.net/"ibernate-$appin --.2.dtd>@ ;"ibernate-$appin @ ;class na$e=>Stor4> table=>stor4>@ ;id na$e=>id> colu$n=>*D> t4pe=>int> unsaved-value=>2>@ ; enerator class=>incre$ent>/@ ;/id@ ;propert4 na$e=>info> colu$n=>*+,O> t4pe=>strin >/@ ;$an4-to-one na$e=>!riter> colu$n=>*D> laJ4=>false>/@ ;/class@ ;/"ibernate-$appin @

Step :- Create 6riter-+ava bean "lasspublic class Jriter { private int id; private String na)e; private List stories; public void setId#int i$ { id ! i; 3 public int getId#$ { return id; 3 public void set=a)e#String n$ { na)e ! n; 3 public String get=a)e#$ { return na)e; 3 public void setStories#List l$ { stories ! l; 3 public List getStories#$ {

return stories; 3 3

Step <- Create Story-+ava bean "lasspublic class Stor( { private int id; private String in o; private Jriter &riter; public Stor(#${ 3 public Stor(#String in o$ { this"in o ! in o; 3 public void setId#int i$ { id ! i; 3 public int getId#$ { return id; 3 public void setIn o#String n$ { in o ! n; 3 public String getIn o#$ { return in o; 3 public void setJriter#Jriter &riter$ { this"&riter ! &riter; 3 public Jriter getJriter#$ { return &riter; 3 3

Step =- add writer-hbm-xml and story-hbm-xml into hibernate-"fg-xml


;<#$l version=F1.2F encodin =Futf-?F<@ ;ltGADOC%BC' "ibernate-confi uration CUB&*C >-//Hibernate/Hibernate Confi uration D%D -.2//'+> >"ttpE//"ibernate.sourcefor e.net/"ibernate-confi uration--.2.dtd>@ ;"ibernate-confi uration@ ;session-factor4@ ;A-- Database connection settin s --@ ;propert4

na$e=>connection.driver:class>@co$.$4s6l.jdbc.Driver;/propert4@ ;propert4 na$e=>connection.url>@jdbcE$4s6lE//local"ostE--20/tec"fa6db;/propert4 @ ;propert4 na$e=>connection.userna$e>@tec"fa6;/propert4@ ;propert4 na$e=>connection.pass!ord>@tec"fa6;/propert4@ ;A-- JDBC connection pool Huse t"e built-inI --@ ;propert4 na$e=>"ibernate.c-p2.$in:siJe>@1;/propert4@ ;propert4 na$e=>"ibernate.c-p2.$a#:siJe>@(;/propert4@ ;propert4 na$e=>"ibernate.c-p2.ti$eout>@1?22;/propert4@ ;propert4 na$e=>"ibernate.c-p2.$a#:state$ents>@72;/propert4@ ;A-- 84S9& dialect//different for different Database --@ ;propert4 na$e=>dialect>@or ."ibernate.dialect.84S9&Dialect;/propert4@ ;A-- 'nable HibernateFs auto$atic session conte#t $ana e$ent --@ ;propert4 na$e=>current:session:conte#t:class>@t"read;/propert4@ ;A-- Disable t"e second-level cac"e --@ ;propert4 na$e=>cac"e.provider:class>@or ."ibernate.cac"e.+oCac"eCrovider;/pro pert4@ ;A-- 'c"o all e#ecuted S9& to stdout --@ ;propert4 na$e=>s"o!:s6l>@true;/propert4@ ;propert4 na$e=>"b$.ddl.auto>@update;/propert4@ ;$appin resource=>stor4."b$.#$l>/@ ;$appin resource=>!riter."b$.#$l>/@ ;/session-factor4@ ;/"ibernate-confi uration@

Hibernate Tutorial Step by Step -- Code Examples


&any to &any )elation in Hibernate

"here are two table E4E-"S and S2EAGE'S . One Event !an have m ltiple spea1ers. And One Spea1er !an spea1 in m ltiple Event. So this is many to many relation. "o maintain this relation we have to introd !e third "AB#E name E4E-"HS2EAGE'S . Step 7- "reate a tables EBE0TS * S@EACE'S and EBE0TDS@EACE'S in your database
create table 'M'+%S H event:id nu$berD //C5*8A5B L'B event:na$e varc"ar

IG create table SC'AL'5S H speaKer:id nu$berD //C5*8A5B L'B speaKer:na$e varc"arD IG create table 'M'+%:SC'AL'5S H elt nu$berD//pri$ar4 Ke4 event:id nu$berD speaKer:id nu$ber IG

Step 8- event-hbm-xml - Hibenate mapping-6hi"h maps to EBE0TS TA!$E


;<#$l version=>1.2><@ ;ADOC%BC' "ibernate-$appin CUB&*C >-//Hibernate/Hibernate 8appin D%D -.2//'+> >"ttpE//"ibernate.sourcefor e.net/"ibernate-$appin --.2.dtd>@ ;"ibernate-$appin @ ;class na$e=>'vent> table=>events>@ ;id na$e=>id> colu$n=>event:id> t4pe=>lon >@ ; enerator class=>incre$ent>/@ ;/id@ ;propert4 na$e=>na$e> colu$n=>event:na$e> t4pe=>strin > len t"=>122>/@ ;set na$e=>speaKers> table=>event:speaKers> cascade=>all>@ ;Ke4 colu$n=>event:id>/@ ;$an4-to-$an4 class=>SpeaKer>/@ ;/set@ ;/class@ ;/"ibernate-$appin @

Step ;- &apping spea3er-hbm-xml- 6hi"h maps to S@EACE'S TA!$E;<#$l version=>1.2><@ ;ADOC%BC' "ibernate-$appin CUB&*C >-//Hibernate/Hibernate 8appin D%D -.2//'+> >"ttpE//"ibernate.sourcefor e.net/"ibernate-$appin --.2.dtd>@ ;"ibernate-$appin @ ;class na$e=>SpeaKer> table=>speaKers>@ ;id na$e=>id> colu$n=>speaKer:id> t4pe=>lon >@ ; enerator class=>incre$ent>/@ ;/id@ ;propert4 na$e=>na$e> colu$n=> speaKer:na$e>

t4pe=>strin > len t"=>122>/@ ;set na$e=>events> table=>event:speaKers> cascade=>all>@ ;Ke4 colu$n=>speaKer:id>/@ ;$an4-to-$an4 class=>'vent>/@ ;/set@ ;/class@ ;/"ibernate-$appin @

Step :- Create Event-+ava bean "lasspublic class 'vent{ private long id; private String na)e; private Set speakers; public void setId#long id$ { this"id ! id; 3 public long getId#$ { return id; 3 public String get=a)e#$ { return na)e; 3 public void set=a)e#String na)e$ { this"na)e ! na)e; 3 public void setSpeakers#Set speakers$ { this"speakers ! speakers; 3 public Set getSpeakers#$ { return speakers; 3 3

Step <- Create Spea3er-+ava bean "lasspublic class Speaker{ private long id; private String na)e; private Set events; public void setId#long id$ { this"id ! id; 3 public long getId#$ {

return id; 3 public String get=a)e#$ { return na)e; 3 public void set=a)e#String na)e$ { this"na)e ! na)e; 3 public Set get'vents#$ { return this"events; 3 public void set'vents#Set events$ { this"events ! events; 3 3

Step =- add event-hbm-xml and spea3er-hbm-xml into hibernate-"fg-xml


;<#$l version=F1.2F encodin =Futf-?F<@ ;ltGADOC%BC' "ibernate-confi uration CUB&*C >-//Hibernate/Hibernate Confi uration D%D -.2//'+> >"ttpE//"ibernate.sourcefor e.net/"ibernate-confi uration--.2.dtd>@ ;"ibernate-confi uration@ ;session-factor4@ ;A-- Database connection settin s --@ ;propert4 na$e=>connection.driver:class>@co$.$4s6l.jdbc.Driver;/propert4@ ;propert4 na$e=>connection.url>@jdbcE$4s6lE//local"ostE--20/tec"fa6db;/propert4 @ ;propert4 na$e=>connection.userna$e>@tec"fa6;/propert4@ ;propert4 na$e=>connection.pass!ord>@tec"fa6;/propert4@ ;A-- JDBC connection pool Huse t"e built-inI --@ ;propert4 na$e=>"ibernate.c-p2.$in:siJe>@1;/propert4@ ;propert4 na$e=>"ibernate.c-p2.$a#:siJe>@(;/propert4@ ;propert4 na$e=>"ibernate.c-p2.ti$eout>@1?22;/propert4@ ;propert4 na$e=>"ibernate.c-p2.$a#:state$ents>@72;/propert4@ ;A-- 84S9& dialect//different for different Database --@ ;propert4 na$e=>dialect>@or ."ibernate.dialect.84S9&Dialect;/propert4@ ;A-- 'nable HibernateFs auto$atic session conte#t $ana e$ent --@ ;propert4 na$e=>current:session:conte#t:class>@t"read;/propert4@ ;A-- Disable t"e second-level cac"e --@ ;propert4

na$e=>cac"e.provider:class>@or ."ibernate.cac"e.+oCac"eCrovider;/pro pert4@ ;A-- 'c"o all e#ecuted S9& to stdout --@ ;propert4 na$e=>s"o!:s6l>@true;/propert4@ ;propert4 na$e=>"b$.ddl.auto>@update;/propert4@ ;$appin resource=>event."b$.#$l>/@ ;$appin resource=>speaKer."b$.#$l>/@ ;/session-factor4@ ;/"ibernate-confi uration@

Here is the "ode ) how to save and fet"h data


'vent event ! ne& 'vent#$; event"set=a)e#*Inverse test*$; event"setSpeakers#ne& HashSet#$$; event"getSpeakers#$"add#ne& Speaker#*6a)*7 event$$; event"getSpeakers#$"add#ne& Speaker#*S(a)*7 event$$; session"save#event$; /// Save /ll the Data event ! #'vent$ session"load#'vent"class7 event"getId#$$; Set speakers ! event"getSpeakers#$; or #Iterator i ! speakers"iterator#$; i"has=ext#$;$ { Speaker speaker ! #Speaker$ i"next#$; S(ste)"out"println#speaker"get:irst=a)e#$$; S(ste)"out"println#speaker"getId#$$; 3

Hibernate Tutorial Step by Step -- Code Examples


H$#' T e Hibernate $uery #anguage %"e Hibernate 9uer4 &an ua e is e#ecuted usin session.create9uer4HI. %"is tutorial includes fro$ clauseDAssociations and joinsD A re ate functionsD%"e order b4 clauseD%"e roup b4 clauseDSub6ueries.

The from "lause


fro$ '$plo4ee // '$plo4ee is class na$e $apped to '8C&OB'' %AB&' or fro$ '$plo4ee as e or fro$ '$plo4ee e !"ere e.e$p*d = -G

&ist e$p&ist = session.create9uer4H>fro$ '$plo4ee>I.listHIG

Asso"iations and +oins


fro$ '$plo4ee e !"ere e.scope8od,la = 1 and pc.isDeleted A =1 &ist e$p&ist = session.create9uer4H>fro$ '$plo4ee e !"ere e.scope8od,la = 1 and pc.isDeleted A= 1>I.listHIG

Aggregate fun"tions
select av Hcat.!ei "tID su$Hcat.!ei "tID $a#Hcat.!ei "tID countHcatI fro$ Cat cat Scrollable5esults rs = session.create9uer4H>select av Hcat.!ei "tID su$Hcat.!ei "tID $a#Hcat.!ei "tID countHcatI fro$ Cat cat>I.scrollHIG ifHrs.ne#tHIIN S4ste$.out.printlnHrs. etH2IIG S4ste$.out.printlnHrs. etH1IIG S4ste$.out.printlnHrs. etH.IIG S4ste$.out.printlnHrs. etH-IIG O

The order by "lause


fro$ '$plo4ee e order b4 e.na$e desc &ist e$p&ist = session.create9uer4H>fro$ '$plo4ee e order b4 e.na$e desc>I.listHIG asc or desc indicate ascendin or descendin order respectivel4.

The group by "lause


select e.deptD su$He.salar4ID countHeI '$plo4ee e roup b4 cat.dept

Sub,ueries
fro$ '$plo4ee as e !"ere e.na$e = so$e H

select na$e.nicK+a$e fro$ +a$e as na$e I

Hibernate Tutorial Step by Step -- Code Examples


Criteria $ueries %"e interface or ."ibernate.Criteria represents a 6uer4 a ainst a particular persistent class. %"e Session is a factor4 for Criteria instances.

Criteria ) Sele"t E from EmployeeCriteria crie$p = session.createCriteriaH'$plo4ee.classIG &ist e$plist = crie$p.listHIG

'estri"tions to narrow result set "he !lass org.hibernate.!riterion.'estri!tions sed to narrow res lt set.
// S'&'C% P ,5O8 '8C&OB'' )H'5' AQ'=.(G ----S9& CO88A+D criteria 6uer4 for above 6uer4 is E &ist e$p&ist = session.createCriteriaH'$plo4ee.classI.addH 5estrictions.e6H>a e>D ne! *nte erH.(I I I.listHIG // +ot '6ual in "ibernate criteria // S'&'C% P ,5O8 '8C&OB'' )H'5' AQ' A=.(G ----S9& CO88A+D criteria 6uer4 for above 6uer4 is E &ist e$p&ist = session.createCriteriaH'$plo4ee.classI.addH 5estrictions.neH>a e>D ne! *nte erH.(I I I.listHIG

Ordering the results


// S'&'C% P ,5O8 '8C&OB'' )H'5' AQ'=.( O5D'5 BB '8C:+A8' D'SCG ----S9& CO88A+D criteria 6uer4 for above 6uer4 is E &ist e$p&ist = session.createCriteriaH'$plo4ee.classI. addH 5estrictions.e6H>a e>D ne! *nte erH.(I I I.addOrderH Order.descH>e$pna$e>I I.listHIG

Asso"iations
// S'&'C% e.na$e ,5O8 '8C&OB'' e D address a !"ere e.address:id=a.address:id and a.countr4=FUSFG ----S9& CO88A+D criteria 6uer4 for above 6uer4 is E &ist e$p&ist = session.createCriteriaH'$plo4ee.classI.createAliasH>address>D>a dd>I. addH 5estrictions.e6H>add.countr4>D >US> I I.listHIG

Example ,ueries "he !lass org.hibernate.!riterion.Example allows yo to !onstr !t a * ery !riterion from a given instan!e.
// S'&'C% P ,5O8 '8C&OB'' e )H'5' e.dept=F*%FG ----S9& CO88A+D criteria 6uer4 for above 6uer4 is E '$plo4ee e$p = ne! '$plo4eeHIG cat.setDeptHF*%FIG &ist e$plist = session.createCriteriaH'$plo4ee.classI .addH '#a$ple.createHe$pI I .listHIG

Hibernate Tutorial Step by Step -- Code Examples


Criteria $ueries ' E*ual +e*,- .ot E*ual+ne,- #ess t an +lt,- #ess t an or e*ual+le,- greater t an +gt,-greater t an or e*ual+ge, and %rdering t e results %"e interface or ."ibernate.Criteria represents a 6uer4 a ainst a particular persistent class. %"e Session is a factor4 for Criteria instances. *n t"is section it s"o! "o! to create %AB&' and COJO Java class and 8appin !it" t"e 9uer4.

Create TA!$E E&@$OAEECreate %AB&' '8C&OB''H id nu$berG na$e varc"arG a e nu$berG IG

Create Employee-+ava bean "lassHibernate ses the 2lain Old Java Ob)e!ts +2OJOs, !lasses to map to the database table +Emp.)ava to E&2#O<EE "AB#E,. 5e !an !onfig re the variables to map to the database !ol mn.
public class ')plo(ee { private long id; private String na)e; private int age; public long getId#$ { return id; 3 private void setId#long id$ { this"id ! id; 3 public String get=a)e#$ { return na)e; 3 public void set=a)e#String na)e$ { this"na)e ! na)e; 3 public int get/ge#$ { return age; 3 private void set/ge#int age$ { this"age ! age; 3 3

Employee-hbm-xml - This mapps E&@$OAEE TA!$E and Emp-+ava


;<#$l version=>1.2><@ ;ADOC%BC' "ibernate-$appin CUB&*C >-//Hibernate/Hibernate 8appin D%D -.2//'+> >"ttpE//"ibernate.sourcefor e.net/"ibernate-$appin --.2.dtd>@ ;"ibernate-$appin @ ;class na$e=>'$plo4ee> table=>'8C&OB''>@ ;id na$e=>id> colu$n=>id> t4pe=>lon >@ ; enerator class=>incre$ent>/@ // %"is enerates t"e pri$ar4 Ke4 ;/id@ ;propert4 na$e=>na$e> colu$n=>na$e>/@ ;propert4 na$e=>a e> colu$n=>a e> t4pe=>int>/@

;/class@ ;/"ibernate-$appin @

E,ual .e,/ E* al +e*, . 7s sed to !he!1 e* al in the * ery.


// S'&'C% P ,5O8 '8C&OB'' )H'5' AQ'=.(G ----S9& CO88A+D criteria 6uer4 for above 6uer4 is E &ist e$p&ist = session.createCriteriaH'$plo4ee.classI.addH 5estrictions.e6H>a e>D ne! *nte erH.(I I I.listHIG

0otE,ual .ne/ -otE* al +ne, . 7s sed to !he!1 not e* al in the * ery.


// S'&'C% P ,5O8 '8C&OB'' )H'5' AQ' A=.(G ----S9& CO88A+D // +ot '6ual in "ibernate criteria criteria 6uer4 for above 6uer4 is E &ist e$p&ist = session.createCriteriaH'$plo4ee.classI.addH 5estrictions.neH>a e>D ne! *nte erH.(I I I.listHIG

$ess than .lt/ #ess than +lt, . 7s sed to !he!1 less than in the * ery.
// S'&'C% P ,5O8 '8C&OB'' )H'5' AQ' ; .(G ----S9& CO88A+D // +ot '6ual in "ibernate criteria criteria 6uer4 for above 6uer4 is E &ist e$p&ist = session.createCriteriaH'$plo4ee.classI.addH 5estrictions.ltH>a e >D ne! *nte erH.(I I I.listHIG

$ess than or e,ual.le/

#ess than or e* al+le, . 7s sed to !he!1 less than or e* al in the * ery.


// S'&'C% P ,5O8 '8C&OB'' )H'5' AQ' ;= .(G ----S9& CO88A+D // +ot '6ual in "ibernate criteria criteria 6uer4 for above 6uer4 is E &ist e$p&ist = session.createCriteriaH'$plo4ee.classI.addH 5estrictions.leH>a e >D ne! *nte erH.(I I I.listHIG

Freater than .gt/ Ireater than +gt, . 7s sed to !he!1 greater than in the * ery.
// S'&'C% P ,5O8 '8C&OB'' )H'5' AQ' @ .(G ----S9& CO88A+D // +ot '6ual in "ibernate criteria criteria 6uer4 for above 6uer4 is E &ist e$p&ist = session.createCriteriaH'$plo4ee.classI.addH 5estrictions. tH>a e>D ne! *nte erH.(I I I.listHIG

Freater than or e,ual .gt/ Ireater than or e* al +gt, . 7s sed to !he!1 greater than or e* al in the * ery.
// S'&'C% P ,5O8 '8C&OB'' )H'5' AQ' @= .(G ----S9& CO88A+D // +ot '6ual in "ibernate criteria criteria 6uer4 for above 6uer4 is E &ist e$p&ist = session.createCriteriaH'$plo4ee.classI.addH 5estrictions. eH>a e>D ne! *nte erH.(I I I.listHIG

Ordering the results


// S'&'C% P ,5O8 '8C&OB'' )H'5' AQ'=.( O5D'5 BB +A8' D'SCG ----S9& CO88A+D criteria 6uer4 for above 6uer4 is E &ist e$p&ist = session.createCriteriaH'$plo4ee.classI. addH 5estrictions.e6H>a e>D ne!

*nte erH.(I I I.addOrderH Order.descH>na$e>I I.listHIG

Hibernate Tutorial Step by Step -- Code Examples


Criteria $ueries' And %) !onditions %"e interface or ."ibernate.Criteria represents a 6uer4 a ainst a particular persistent class. %"e Session is a factor4 for Criteria instances. *n t"is section it s"o! "o! to create %AB&' and COJO Java class and 8appin !it" t"e 9uer4.

Create TA!$E E&@$OAEECreate %AB&' '8C&OB''H id nu$berG na$e varc"arG a e nu$berG IG

Create Employee-+ava bean "lassHibernate ses the 2lain Old Java Ob)e!ts +2OJOs, !lasses to map to the database table +Emp.)ava to E&2#O<EE "AB#E,. 5e !an !onfig re the variables to map to the database !ol mn.
public class ')plo(ee { private long id; private String na)e; private int age; public long getId#$ { return id; 3 private void setId#long id$ { this"id ! id; 3 public String get=a)e#$ { return na)e; 3 public void set=a)e#String na)e$ { this"na)e ! na)e;

3 public int get/ge#$ { return age; 3 private void set/ge#int age$ { this"age ! age; 3 3

Employee-hbm-xml - This mapps E&@$OAEE TA!$E and Emp-+ava


;<#$l version=>1.2><@ ;ADOC%BC' "ibernate-$appin CUB&*C >-//Hibernate/Hibernate 8appin D%D -.2//'+> >"ttpE//"ibernate.sourcefor e.net/"ibernate-$appin --.2.dtd>@ ;"ibernate-$appin @ ;class na$e=>'$plo4ee> table=>'8C&OB''>@ ;id na$e=>id> colu$n=>id> t4pe=>lon >@ ; enerator class=>incre$ent>/@ // %"is enerates t"e pri$ar4 Ke4 ;/id@ ;propert4 na$e=>na$e> colu$n=>na$e>/@ ;propert4 na$e=>a e> colu$n=>a e> t4pe=>int>/@ ;/class@ ;/"ibernate-$appin @

And Condtion "his method ret rns the !on) n!tions of two expressions. Both !onditions are ;tr e; then it ex! tes the * ery otherwise not.
// S'&'C% P ,5O8 '8C&OB'' )H'5' AQ'=.( A+D AQ'=.?G ----S9& CO88A+D criteria 6uer4 for above 6uer4 is E &ist e$p&ist = session.createCriteriaH'$plo4ee.classI .addH 5estrictions.e6H>a e>D ne! *nte erH.(I I I .addH 5estrictions.e6H>a e>D ne! *nte erH.?I I I .listHIG

O' Condtion

"his method ret rns the dis) !tion of two expressions. Any given !ondition is ;tr e; then it exe! tes the * ery. 7n this t torial( JorJ is sed
// S'&'C% P ,5O8 '8C&OB'' )H'5' AQ'=.( O5 AQ'=.?G ----S9& CO88A+D criteria 6uer4 for above 6uer4 is E &ist e$p&ist = session.createCriteriaH'$plo4ee.classI .addH'#pression.orH '#pression.e6H>a e>D ne! *nte erH.(I I ID '#pression.e6H>a e>D ne! *nte erH.?I I II .listHIG

Hibernate Tutorial Step by Step -- Code Examples


Hibernate /generator0 to generate id +primary 1ey,

"he optional /generator0 !hild element names a Java !lass sed to generate ni* e identifiers for instan!es of the persistent !lass increment generates identifiers of type long( short or int that are ni* e only when no other pro!ess is inserting data into the same table. Do not se in a !l ster. 8ollow the setps . Step 7- "reate a table name E&@$OAEE in your database
// for 84S9& create table '8C&OB'' H id bi intH.2I D na$e varc"ar IG // ,O5 O5AC&' create table '8C&OB'' H id nu$berG na$e varc"ar IG

Step 8- Create Emp-+ava bean "lassHibernate ses the 2lain Old Java Ob)e!ts +2OJOs, !lasses to map to the database table +Emp.)ava to E&2#O<EE "AB#E,. 5e !an !onfig re the variables to map to the database !ol mn.

public class ')p { private long id; private String na)e; public long getId#$ { return id; 3 private void setId#long id$ { this"id ! id; 3 public String get=a)e#$ { return na)e; 3 public void set=a)e#String na)e$ { this"na)e ! na)e; 3 3

Step ;- Emp-hbm-xml - This mapps E&@$OAEE TA!$E and Emp-+ava ) increment for the generator "lass
;<#$l version=>1.2><@ ;ADOC%BC' "ibernate-$appin CUB&*C >-//Hibernate/Hibernate 8appin D%D -.2//'+> >"ttpE//"ibernate.sourcefor e.net/"ibernate-$appin --.2.dtd>@ ;"ibernate-$appin @ ;class na$e=>'$p> table=>'8C&OB''>@ ;id na$e=>id> colu$n=>id> t4pe=>lon >@ ; enerator class=>incre$ent>/@ // %"is enerates t"e pri$ar4 Ke4 ;/id@ ;propert4 na$e=>na$e> colu$n=>na$e>/@ ;/class@ ;/"ibernate-$appin @

Step :- add Emp-hbm-xml into hibernate-"fg-xml Hibernate provided !onne!tion pooling sning !=pB and transa!tion management . Hibernate ses the hibernate.!fg.xml to !reate the !onne!tion pool and set p re* ired environment
;<#$l version=F1.2F encodin =Futf-?F<@ ;ltGADOC%BC' "ibernate-confi uration CUB&*C >-//Hibernate/Hibernate Confi uration D%D -.2//'+>

>"ttpE//"ibernate.sourcefor e.net/"ibernate-confi uration--.2.dtd>@ ;"ibernate-confi uration@ ;session-factor4@ ;A-- Database connection settin s --@ ;propert4 na$e=>connection.driver:class>@co$.$4s6l.jdbc.Driver;/propert4@ ;propert4 na$e=>connection.url>@jdbcE$4s6lE//local"ostE--20/tec"fa6db;/propert4 @ ;propert4 na$e=>connection.userna$e>@tec"fa6;/propert4@ ;propert4 na$e=>connection.pass!ord>@tec"fa6;/propert4@ ;A-- JDBC connection pool Huse t"e built-inI --@ ;propert4 na$e=>"ibernate.c-p2.$in:siJe>@1;/propert4@ ;propert4 na$e=>"ibernate.c-p2.$a#:siJe>@(;/propert4@ ;propert4 na$e=>"ibernate.c-p2.ti$eout>@1?22;/propert4@ ;propert4 na$e=>"ibernate.c-p2.$a#:state$ents>@72;/propert4@ ;A-- 84S9& dialect//different for different Database --@ ;propert4 na$e=>dialect>@or ."ibernate.dialect.84S9&Dialect;/propert4@ ;A-- 'nable HibernateFs auto$atic session conte#t $ana e$ent --@ ;propert4 na$e=>current:session:conte#t:class>@t"read;/propert4@ ;A-- Disable t"e second-level cac"e --@ ;propert4 na$e=>cac"e.provider:class>@or ."ibernate.cac"e.+oCac"eCrovider;/pro pert4@ ;A-- 'c"o all e#ecuted S9& to stdout --@ ;propert4 na$e=>s"o!:s6l>@true;/propert4@ ;propert4 na$e=>"b$.ddl.auto>@update;/propert4@ ;$appin resource=>'$p."b$.#$l>/@ ;/session-factor4@ ;/"ibernate-confi uration@

Step <- hibernate automati"ally in"rement id using generator Hibernate Session is the main r ntime interfa!e for Hibernate whi!h is sed for DataBase operataion. Session has the method li1e save +, ( pdate +, ( !rete% ery+, for Data Base operation. <o !an get session sing Session8a!tory.openSession+, method. Session8a!tory allows appli!ation to !reate the Hibernate Sesssion by reading the !onfig ration from hibernate.!fg.xml file. "hen the save +, method on session ob)e!t is sed to save the !onta!t information to the database.
public class -est'xa)ple { public static void )ain#StringAB args$ {

Session session ! null; tr({ // -his step &ill read hibernate"c g"x)l Session:actor( session:actor( ! ne& %on iguration#$"con igure#$"buildSession:actor(#$; session !session:actor("openSession#$; S(ste)"out"println#*Inserting 6ecords*$; ')p e)p? ! ne& ')p#$; e)p?"set=a)e#*=ick*$; session"save#e)p?$; // Je are =ot adding id 7 hibernate auto)aticall( incre)ent the value ')p e)pC ! ne& ')p#$; e)pC"set=a)e#*Das*$; session"save#e)pC$; // Je are =ot adding id 7 hibernate auto)aticall( incre)ent the value session" lush#$; // insert data into databse S(ste)"out"println#*Save DoneD inish database insert*$; // =o& etch the ')plo(ee data List e)pList ! session"createEuer(#* ro) ')p*$"list#$; //e)pList contains the list o ')plo(ee or#int i!F;i ')p e)p ! #')p$e)pList"get#i$; S(ste)"out"println#e)p"getId#$$; S(ste)"out"println#e)p"get=a)e#$$; 3 // 9ut put is . ? =ick C Das 3catch#'xception e${ 3 inall({ session"close#$; 3 3 3

Hibernate Tutorial Step by Step -- Code Examples


2revent !on!urrent update in Hibernate

"his t torial resolve the iss e of 6ser thin1 time . + one ser edit the re!ord for pdate and thin1ing and !hanging val es ( same time other ser edit the same re!ord and pdate. then first ser pdate and :nd ser;s data is lost., <o !an say this is version "he"3ing in Hibernate or perevent slate ob+e"t updatation in Hibernate. version !he!1ing sed in hibernate when more then one thread trying to a!!ess same

data. 8or example . 6ser A edit the row of the "AB#E for pdate + 7n the 6ser 7nterfa!e !hanging data $ "his is ser thin1ing time, and in the same time 6ser B edit the same re!ord for pdate and !li!1 the pdate. "hen 6ser A !li!1 the 6pdate and pdate done. Chnage made by ser B is lost. 7n hibernate yo !an perevent slate ob)e!t pdatation sing version !he!1ing. Che!1 the version of the row when yo are pding the row. Iet the version of the row when yo are fet!hing the row of the "AB#E for pdate. On the time of pdation ) st fet!h the version n mber and mat!h with yo r version n mber + on the time of fet!hing,. Below steps to prevent !on! rrent pdate in Hibernate. Step 7- e"lare a variable Gversion4dG in your bean Class with setter and getter methodpublic class Jriter { private int id; private String na)e; private long versionId; public void setId#int i$ { id ! i; 3 public int getId#$ { return id; 3 public void set=a)e#String n$ { na)e ! n; 3 public String get=a)e#$ { return na)e; 3 public long getGersionId#$ { return versionId; 3 public void setGersionId#long versionId$ { this"versionId ! versionId; 3 3

Step 8- Add Extra "oulmn name GversionG in the 6'4TE' TA!$Ecreate table )5*%'5 H *D nu$berD //C5*8A5B L'B +A8' varc"arD version nu$ber IG

Step ;- Add property in writer-hbm-xml and optimisti"-lo"3HGversionG - 6hi"h maps to 6'4TE' TA!$E;<#$l version=>1.2><@ ;ADOC%BC' "ibernate-$appin CUB&*C >-//Hibernate/Hibernate 8appin D%D -.2//'+> >"ttpE//"ibernate.sourcefor e.net/"ibernate-$appin --.2.dtd>@ ;"ibernate-$appin @ ;class na$e=>)riter> table=>)5*%'5> opti$isticlocK=>version>@ ;id na$e=>id> colu$n=>*D> t4pe=>int> unsaved-value=>2>@ ; enerator class=>incre$ent>/@ ;/id@ ;propert4 na$e=>na$e> colu$n=>+A8'> t4pe=>strin >/@ ;version na$e=>version*d> t4pe=>lon > colu$n=>version> /@ ;/class@ ;/"ibernate-$appin @

Step :- add writer-hbm-xml into hibernate-"fg-xml


;<#$l version=F1.2F encodin =Futf-?F<@ ;ltGADOC%BC' "ibernate-confi uration CUB&*C >-//Hibernate/Hibernate Confi uration D%D -.2//'+> >"ttpE//"ibernate.sourcefor e.net/"ibernate-confi uration--.2.dtd>@ ;"ibernate-confi uration@ ;session-factor4@ ;A-- Database connection settin s --@ ;propert4 na$e=>connection.driver:class>@co$.$4s6l.jdbc.Driver;/propert4@ ;propert4 na$e=>connection.url>@jdbcE$4s6lE//local"ostE--20/tec"fa6db;/propert4 @ ;propert4 na$e=>connection.userna$e>@tec"fa6;/propert4@ ;propert4 na$e=>connection.pass!ord>@tec"fa6;/propert4@ ;A-- JDBC connection pool Huse t"e built-inI --@ ;propert4 na$e=>"ibernate.c-p2.$in:siJe>@1;/propert4@ ;propert4 na$e=>"ibernate.c-p2.$a#:siJe>@(;/propert4@ ;propert4 na$e=>"ibernate.c-p2.ti$eout>@1?22;/propert4@ ;propert4 na$e=>"ibernate.c-p2.$a#:state$ents>@72;/propert4@ ;A-- 84S9& dialect//different for different Database --@ ;propert4 na$e=>dialect>@or ."ibernate.dialect.84S9&Dialect;/propert4@ ;A-- 'nable HibernateFs auto$atic session conte#t $ana e$ent --@

;propert4 na$e=>current:session:conte#t:class>@t"read;/propert4@ ;A-- Disable t"e second-level cac"e --@ ;propert4 na$e=>cac"e.provider:class>@or ."ibernate.cac"e.+oCac"eCrovider;/pro pert4@ ;A-- 'c"o all e#ecuted S9& to stdout --@ ;propert4 na$e=>s"o!:s6l>@true;/propert4@ ;propert4 na$e=>"b$.ddl.auto>@update;/propert4@ ;$appin resource=>!riter."b$.#$l>/@ ;/session-factor4@ ;/"ibernate-confi uration@

Step <- 4n the Code 5hen yo are pdating the table ) st !he!1 the version with yo and the ! rrent version in the table. <o !an handle StaleOb)e!tStateEx!eption+, and do what ever yo want. <o !an display error message. Hibernate a t mati!ally !reateK pdate the version n mber when yo pdateKinsert any row in the table.
In the code session ! s "openSession#$; long oldGersion ! &riter"getGersionId#$; // User -hink ti)e ............... 2a( be ? )inute then get the current version using load#$ )ethod belo&" session"load# &riter7 &riter"getId#$ $; // current version in the table i # oldGersionK!&riter"getGersionId#$ $ thro& ne& Stale9b8ectState'xception#$; //check the version &ith (ou and the current version in the table &riter"set=a)e#*Das*$; session" lush#$; session"connection#$"co))it#$; session"close#$;

Hibernate Tutorial Step by Step -- Code Examples

2revent !on!urrent update in Hibernate

"his t torial resolve the iss e of 6ser thin1 time . + one ser edit the re!ord for pdate and thin1ing and !hanging val es ( same time other ser edit the same re!ord and pdate. then first ser pdate and :nd ser;s data is lost., <o !an say this is version "he"3ing in Hibernate or perevent slate ob+e"t updatation in Hibernate. version !he!1ing sed in hibernate when more then one thread trying to a!!ess same data. 8or example . 6ser A edit the row of the "AB#E for pdate + 7n the 6ser 7nterfa!e !hanging data $ "his is ser thin1ing time, and in the same time 6ser B edit the same re!ord for pdate and !li!1 the pdate. "hen 6ser A !li!1 the 6pdate and pdate done. Chnage made by ser B is lost. 7n hibernate yo !an perevent slate ob)e!t pdatation sing version !he!1ing. Che!1 the version of the row when yo are pding the row. Iet the version of the row when yo are fet!hing the row of the "AB#E for pdate. On the time of pdation ) st fet!h the version n mber and mat!h with yo r version n mber + on the time of fet!hing,. Below steps to prevent !on! rrent pdate in Hibernate. Step 7- e"lare a variable Gversion4dG in your bean Class with setter and getter methodpublic class Jriter { private int id; private String na)e; private long versionId; public void setId#int i$ { id ! i; 3 public int getId#$ { return id; 3 public void set=a)e#String n$ { na)e ! n; 3 public String get=a)e#$ { return na)e; 3 public long getGersionId#$ { return versionId; 3 public void setGersionId#long versionId$ { this"versionId ! versionId; 3 3

Step 8- Add Extra "oulmn name GversionG in the 6'4TE' TA!$E-

create table )5*%'5 H *D nu$berD //C5*8A5B L'B +A8' varc"arD version nu$ber IG

Step ;- Add property in writer-hbm-xml and optimisti"-lo"3HGversionG - 6hi"h maps to 6'4TE' TA!$E;<#$l version=>1.2><@ ;ADOC%BC' "ibernate-$appin CUB&*C >-//Hibernate/Hibernate 8appin D%D -.2//'+> >"ttpE//"ibernate.sourcefor e.net/"ibernate-$appin --.2.dtd>@ ;"ibernate-$appin @ ;class na$e=>)riter> table=>)5*%'5> opti$isticlocK=>version>@ ;id na$e=>id> colu$n=>*D> t4pe=>int> unsaved-value=>2>@ ; enerator class=>incre$ent>/@ ;/id@ ;propert4 na$e=>na$e> colu$n=>+A8'> t4pe=>strin >/@ ;version na$e=>version*d> t4pe=>lon > colu$n=>version> /@ ;/class@ ;/"ibernate-$appin @

Step :- add writer-hbm-xml into hibernate-"fg-xml


;<#$l version=F1.2F encodin =Futf-?F<@ ;ltGADOC%BC' "ibernate-confi uration CUB&*C >-//Hibernate/Hibernate Confi uration D%D -.2//'+> >"ttpE//"ibernate.sourcefor e.net/"ibernate-confi uration--.2.dtd>@ ;"ibernate-confi uration@ ;session-factor4@ ;A-- Database connection settin s --@ ;propert4 na$e=>connection.driver:class>@co$.$4s6l.jdbc.Driver;/propert4@ ;propert4 na$e=>connection.url>@jdbcE$4s6lE//local"ostE--20/tec"fa6db;/propert4 @ ;propert4 na$e=>connection.userna$e>@tec"fa6;/propert4@ ;propert4 na$e=>connection.pass!ord>@tec"fa6;/propert4@ ;A-- JDBC connection pool Huse t"e built-inI --@ ;propert4 na$e=>"ibernate.c-p2.$in:siJe>@1;/propert4@

;propert4 na$e=>"ibernate.c-p2.$a#:siJe>@(;/propert4@ ;propert4 na$e=>"ibernate.c-p2.ti$eout>@1?22;/propert4@ ;propert4 na$e=>"ibernate.c-p2.$a#:state$ents>@72;/propert4@ ;A-- 84S9& dialect//different for different Database --@ ;propert4 na$e=>dialect>@or ."ibernate.dialect.84S9&Dialect;/propert4@ ;A-- 'nable HibernateFs auto$atic session conte#t $ana e$ent --@ ;propert4 na$e=>current:session:conte#t:class>@t"read;/propert4@ ;A-- Disable t"e second-level cac"e --@ ;propert4 na$e=>cac"e.provider:class>@or ."ibernate.cac"e.+oCac"eCrovider;/pro pert4@ ;A-- 'c"o all e#ecuted S9& to stdout --@ ;propert4 na$e=>s"o!:s6l>@true;/propert4@ ;propert4 na$e=>"b$.ddl.auto>@update;/propert4@ ;$appin resource=>!riter."b$.#$l>/@ ;/session-factor4@ ;/"ibernate-confi uration@

Step <- 4n the Code 5hen yo are pdating the table ) st !he!1 the version with yo and the ! rrent version in the table. <o !an handle StaleOb)e!tStateEx!eption+, and do what ever yo want. <o !an display error message. Hibernate a t mati!ally !reateK pdate the version n mber when yo pdateKinsert any row in the table.
In the code session ! s "openSession#$; long oldGersion ! &riter"getGersionId#$; // User -hink ti)e ............... 2a( be ? )inute then get the current version using load#$ )ethod belo&" session"load# &riter7 &riter"getId#$ $; // current version in the table i # oldGersionK!&riter"getGersionId#$ $ thro& ne& Stale9b8ectState'xception#$; //check the version &ith (ou and the current version in the table &riter"set=a)e#*Das*$; session" lush#$; session"connection#$"co))it#$; session"close#$;

Hibernate Tutorial Step by Step -- Code Examples


2revent !on!urrent update in Hibernate

"his t torial resolve the iss e of 6ser thin1 time . + one ser edit the re!ord for pdate and thin1ing and !hanging val es ( same time other ser edit the same re!ord and pdate. then first ser pdate and :nd ser;s data is lost., <o !an say this is version "he"3ing in Hibernate or perevent slate ob+e"t updatation in Hibernate. version !he!1ing sed in hibernate when more then one thread trying to a!!ess same data. 8or example . 6ser A edit the row of the "AB#E for pdate + 7n the 6ser 7nterfa!e !hanging data $ "his is ser thin1ing time, and in the same time 6ser B edit the same re!ord for pdate and !li!1 the pdate. "hen 6ser A !li!1 the 6pdate and pdate done. Chnage made by ser B is lost. 7n hibernate yo !an perevent slate ob)e!t pdatation sing version !he!1ing. Che!1 the version of the row when yo are pding the row. Iet the version of the row when yo are fet!hing the row of the "AB#E for pdate. On the time of pdation ) st fet!h the version n mber and mat!h with yo r version n mber + on the time of fet!hing,. Below steps to prevent !on! rrent pdate in Hibernate. Step 7- e"lare a variable Gversion4dG in your bean Class with setter and getter methodpublic class Jriter { private int id; private String na)e; private long versionId; public void setId#int i$ { id ! i; 3 public int getId#$ { return id; 3 public void set=a)e#String n$ { na)e ! n; 3 public String get=a)e#$ { return na)e; 3 public long getGersionId#$ { return versionId; 3 public void setGersionId#long versionId$ { this"versionId ! versionId; 3 3

Step 8- Add Extra "oulmn name GversionG in the 6'4TE' TA!$Ecreate table )5*%'5 H *D nu$berD //C5*8A5B L'B +A8' varc"arD version nu$ber IG

Step ;- Add property in writer-hbm-xml and optimisti"-lo"3HGversionG - 6hi"h maps to 6'4TE' TA!$E;<#$l version=>1.2><@ ;ADOC%BC' "ibernate-$appin CUB&*C >-//Hibernate/Hibernate 8appin D%D -.2//'+> >"ttpE//"ibernate.sourcefor e.net/"ibernate-$appin --.2.dtd>@ ;"ibernate-$appin @ ;class na$e=>)riter> table=>)5*%'5> opti$isticlocK=>version>@ ;id na$e=>id> colu$n=>*D> t4pe=>int> unsaved-value=>2>@ ; enerator class=>incre$ent>/@ ;/id@ ;propert4 na$e=>na$e> colu$n=>+A8'> t4pe=>strin >/@ ;version na$e=>version*d> t4pe=>lon > colu$n=>version> /@ ;/class@ ;/"ibernate-$appin @

Step :- add writer-hbm-xml into hibernate-"fg-xml


;<#$l version=F1.2F encodin =Futf-?F<@ ;ltGADOC%BC' "ibernate-confi uration CUB&*C >-//Hibernate/Hibernate Confi uration D%D -.2//'+> >"ttpE//"ibernate.sourcefor e.net/"ibernate-confi uration--.2.dtd>@ ;"ibernate-confi uration@ ;session-factor4@ ;A-- Database connection settin s --@ ;propert4 na$e=>connection.driver:class>@co$.$4s6l.jdbc.Driver;/propert4@ ;propert4 na$e=>connection.url>@jdbcE$4s6lE//local"ostE--20/tec"fa6db;/propert4 @ ;propert4 na$e=>connection.userna$e>@tec"fa6;/propert4@ ;propert4 na$e=>connection.pass!ord>@tec"fa6;/propert4@

;A-- JDBC connection pool Huse t"e built-inI --@ ;propert4 na$e=>"ibernate.c-p2.$in:siJe>@1;/propert4@ ;propert4 na$e=>"ibernate.c-p2.$a#:siJe>@(;/propert4@ ;propert4 na$e=>"ibernate.c-p2.ti$eout>@1?22;/propert4@ ;propert4 na$e=>"ibernate.c-p2.$a#:state$ents>@72;/propert4@ ;A-- 84S9& dialect//different for different Database --@ ;propert4 na$e=>dialect>@or ."ibernate.dialect.84S9&Dialect;/propert4@ ;A-- 'nable HibernateFs auto$atic session conte#t $ana e$ent --@ ;propert4 na$e=>current:session:conte#t:class>@t"read;/propert4@ ;A-- Disable t"e second-level cac"e --@ ;propert4 na$e=>cac"e.provider:class>@or ."ibernate.cac"e.+oCac"eCrovider;/pro pert4@ ;A-- 'c"o all e#ecuted S9& to stdout --@ ;propert4 na$e=>s"o!:s6l>@true;/propert4@ ;propert4 na$e=>"b$.ddl.auto>@update;/propert4@ ;$appin resource=>!riter."b$.#$l>/@ ;/session-factor4@ ;/"ibernate-confi uration@

Step <- 4n the Code 5hen yo are pdating the table ) st !he!1 the version with yo and the ! rrent version in the table. <o !an handle StaleOb)e!tStateEx!eption+, and do what ever yo want. <o !an display error message. Hibernate a t mati!ally !reateK pdate the version n mber when yo pdateKinsert any row in the table.
In the code session ! s "openSession#$; long oldGersion ! &riter"getGersionId#$; // User -hink ti)e ............... 2a( be ? )inute then get the current version using load#$ )ethod belo&" session"load# &riter7 &riter"getId#$ $; // current version in the table i # oldGersionK!&riter"getGersionId#$ $ thro& ne& Stale9b8ectState'xception#$; //check the version &ith (ou and the current version in the table &riter"set=a)e#*Das*$; session" lush#$; session"connection#$"co))it#$; session"close#$;

3ntegrate Struts Spring Hibernate 4eb Appli!ation


"his t torial g ide yo to 7ntegrate Str ts Spring Hibernate in a web appli!ation. Str ts . 4iew +6ser 7nterfa!e, Spring . Servi!e #ayer Hibernate . DAO layer

Here is the steps for 7ntegration Str ts Spring Hibernate 5eb Appli!ation Aou "an download the "ode with 9ip-- strutsspringhibernate-9ipCode is ready--+ust download and run in tom"at-- Cli"3 donate button
Steps to run t"e do!nloded code E step 1. unJip t"e do!nloaded Jip file to DERto$catR!ebappsR director4. step .. DERto$catRbin @ stratup.bat step -. Qo to bro!ser and t4pe t"e U5& E "ttpE//local"ostE?2?2/strutssprin "ibernate/user,or$.do

step >. Enter 6ser -ame and Department and s bmit the JsaveJ b tton.

Here is t e !ode Explanation

Struts 2art
Step 7- Add A"tionServlet in web-xml
ActionServlet ActionServlet is t"e controller in Struts. ActionServlet loads t"e struts-confi .#$l. On load-on-startup t"e servlet container *nstantiate t"e ActionServlet .

"irst Tas1 by A!tionServlet ' %"e ActionServlet taKes t"e Struts Confi file na$e as an init-para$. At startupD in t"e initHI $et"odD t"e ActionServlet reads t"e Struts Confi file and load into $e$or4. Se!ond Tas1 by A!tionServlet ' *f t"e user t4pes "ttpE//local"ostE?2?1/strutssprin "ibernate/user,or$.do in t"e bro!ser U5& barD t"e U5& !ill be intercepted and processed b4 t"e ActionServlet since t"e U5& "as a pattern P.doD !it" a suffi# of >do>. Because servlet-$appin is ;servlet-$appin @ ;servlet-na$e@action;/servlet-na$e@ ;url-pattern@P.do;/url-pattern@ ;/servlet-$appin @ T ird Tas1 by A!tionServlet ' %"en ActionServlet dele ates t"e re6uest "andlin to anot"er class called )e*uest2ro!essor b4 invoKin its processHI $et"od. ;servlet@ ;servlet-na$e@action;/servlet-na$e@ ;servlet-class@or .apac"e.struts.action.ActionServlet;/servlet-class@ ;init-para$@ ;para$-na$e@confi ;/para$-na$e@ ;para$-value@/)'B-*+,/struts-confi .#$l;/para$-value@ ;/init-para$@ ;load-on-startup@1;/load-on-startup@ ;/servlet@ ;servlet-$appin @ ;servlet-na$e@action;/servlet-na$e@ ;url-pattern@P.do;/url-pattern@ ;/servlet-$appin @

Step 8- add A"tion&apping in struts-"onfig-xml http.KKlo!alhost.CBC9Kstr tsspringhibernateK ser8orm.do !all to K)spK ser8orm.)sp )sp.

;<#$l version=>1.2> encodin =>*SO-??73-1> <@ ;ADOC%BC' struts-confi CUB&*C >-//Apac"e Soft!are ,oundation//D%D Struts Confi uration 1..//'+> >"ttpE//jaKarta.apac"e.or /struts/dtds/struts-confi :1:..dtd>@ ;struts-confi @ ;for$-beans@

;for$-bean na$e=>User,or$> t4pe=>co$.User,or$>@ ;/for$-bean@ ;/for$-beans@

;action-$appin s@ ;action pat"=>/user,or$> t4pe=>or .apac"e.struts.actions.,or!ardAction> para$eter=>/jsp/user,or$.jsp>/@ ;action pat"=>/saveUser> t4pe=>co$.UserSaveAction> na$e=>User,or$> scope=>re6uest> validate=>false> input=>/pa es/*nput.jsp>@ ;for!ard na$e=>success> pat"=>/jsp/success.jsp>/@ ;/action@ ;/action-$appin s@

;/struts-confi @

Enter sername and deptname and !li!1 the Save b tton. Save b tton !alls Ksave6ser.do ( save6ser.do !alls !om.6serSaveA!tion based on above !onfig ration in str ts$!onfig.xml. Step ;- user#orm-+sp and su""ess-+sp
user,or$.jsp is t"e for$ !"ere 4ou enter t"e User +a$e and Depart$ent
LM5 taglib uri!*/J'BDI=:/strutsDht)l"tld* pre ix!*ht)l*MN LM5 taglib uri!*/J'BDI=:/strutsDbean"tld* pre ix!*bean*MN Lht)l. or) action!*/saveUser"do* )ethod!*post*N User =a)e . Lht)l.text propert(!*user=a)e* si,e!*OF* )axlength!*?CF*/N LbrN Depart)ent . Lht)l.text propert(!*dept=a)e* si,e!*OF* )axlength!*?CF*/N LbrN

Lht)l.sub)itNSaveL/ht)l.sub)itN L/ht)l. or)N

success.jsp ;".@User Data saved ;/".@ !om5(serSaveA!tion56ava UserSaveAction et t"e user entered infor$ation H5e6uestCrocessor set t"e user entered data into t"e User,or$I. Qet t"e service fro$ applicationConte#t.#$l usin UserService userservice = HUserServiceI Service,inder. etConte#tHre6uestI . etBeanH>userservice>IG *n t"e Action class just et t"e data fro$ User,or$ and call to userservice.saveUserHuserbeanIG
package co); i)port 8avax"servlet"http"HttpServlet6e4uest; i)port 8avax"servlet"http"HttpServlet6esponse; i)port i)port i)port i)port org"apache"struts"action"/ction; org"apache"struts"action"/ction:or); org"apache"struts"action"/ction:or&ard; org"apache"struts"action"/ction2apping;

public class UserSave/ction extends /ction{ public /ction:or&ard execute# /ction2apping )apping7 /ction:or) or)7 HttpServlet6e4uest re4uest7 HttpServlet6esponse response$ thro&s 'xception{

UserService userservice ! #UserService$ Service:inder"get%ontext#re4uest$ "getBean#*userservice*$; User:or) user:or) ! #User:or)$ or); UserBean userbean ! ne& UserBean#$; userbean"setUser=a)e#user:or)"getUser=a)e#$$; userbean"setDept=a)e#user:or)"getDept=a)e#$$; userservice"saveUser#userbean$; return )apping" ind:or&ard#*success*$;

3 3

!om5(ser"orm56ava User,or$ is t"e ,or$ !"ic" contain t"e entered user infor$ation. H5e6uestCrocessor set t"e user entered data into t"e User,or$I.
package co); i)port org"apache"struts"action"/ction:or);

public class User:or) extends /ction:or){ String user=a)e; String dept=a)e; /** * 5return 6eturns the dept=a)e" */ public String getDept=a)e#$ { return dept=a)e; 3 /** * 5para) dept=a)e -he dept=a)e to set" */ public void setDept=a)e#String dept=a)e$ { this"dept=a)e ! dept=a)e; 3 /** * 5return 6eturns the user=a)e" */ public String getUser=a)e#$ { return user=a)e; 3 /** * 5para) user=a)e -he user=a)e to set" */ public void setUser=a)e#String user=a)e$ { this"user=a)e ! user=a)e; 3 3

Spring 2art

Step 7- Add Context$oaderServlet in web-xml


ContextLoaderServlet Conte#t&oaderServlet re ister an /pplication%ontext usin t"e t"e belo! confi uration in !eb.#$l file. Bou can et an4 service HDefind in applicationConte#t.#$lI usin re6uest. etSessionHI. etServletConte#tHI. etBeanH>userservice>IG

;para$-na$e@conte#tConfi &ocation;/para$-na$e@ ;para$-value@/)'B-*+,/applicationConte#t.#$l;/para$-value@ ;/conte#t-para$@ ;servlet@ ;servlet-na$e@conte#t;/servlet-na$e@ ;servletclass@or .sprin fra$e!orK.!eb.conte#t.Conte#t&oaderServlet;/servletclass@ ;load-on-startup@1;/load-on-startup@ ;/servlet@

Step 8- appli"ationContext-xml appli!ationContext.xml !ontains all the Dependen!y 7n)e!tions . And it !ontains hibernate Session8a!tory information also. Here Hibernate integatred with Spring. serservi!e ob)e!t has serdao ob)e!t as setter 7n)e!tion serdao ob)e!t has session8a!tory ob)e!t as setter 7n)e!tion.

;<#$l version=>1.2> encodin =>U%,-?><@ ;ADOC%BC' beans CUB&*C >-//SC5*+Q//D%D B'A+//'+> >"ttpE//!!!.sprin fra$e!orK.or /dtd/sprin -beans.dtd>@ ;beans@ ;bean id=>$4DataSource> class=>or .apac"e.co$$ons.dbcp.BasicDataSource> destro4$et"od=>close>@ ;propert4 na$e=>driverClass+a$e>@;value@co$.$4s6l.jdbc.Driver;/value@;/pro pert4@ ;propert4

na$e=>url>@;value@jdbcE$4s6lE//local"ostE--20/tec"fa6;/value@;/prop ert4@ ;propert4 na$e=>userna$e>@;value@tec"fa6;/value@;/propert4@ ;propert4 na$e=>pass!ord>@;value@tec"fa6;/value@;/propert4@ ;/bean@ ;bean id=>$4Session,actor4> class=>or .sprin fra$e!orK.or$."ibernate-.&ocalSession,actor4Bean>@ ;propert4 na$e=>dataSource>@;ref bean=>$4DataSource>/@;/propert4@ ;propert4 na$e=>$appin 5esources>@ ;list@ ;value@/co$/user."b$.#$l;/value@ ;/list@ ;/propert4@ ;propert4 na$e=>"ibernateCroperties>@ ;value@ "ibernate.dialect=or ."ibernate.dialect.84S9&Dialect ;/value@ ;/propert4@ ;/bean@ ;bean id=>userdao> class=>co$.UserDAO>@ ;propert4 na$e=>session,actor4>@;ref bean=>$4Session,actor4>/@;/propert4@ ;/bean@ ;bean id=>userservice> class=>co$.UserService>@ ;propert4 na$e=>userdao>@;ref bean=>userdao>/@;/propert4@ ;/bean@ ;/beans@ !om5(serServi!e56ava
package co); public class UserService { private UserD/9 userdao; public void saveUser#UserBean user${ getUserdao#$"saveUser#user$;

3 /** * 5return 6eturns the userdao" */ public UserD/9 getUserdao#$ { return userdao; 3 /** * 5para) userdao -he userdao to set" */ public void setUserdao#UserD/9 userdao$ { this"userdao ! userdao; 3 3

!om5Servi!e"inder56ava
package co); i)port org"spring ra)e&ork"context"/pplication%ontext; i)port org"spring ra)e&ork"&eb"context"support"Jeb/pplication%ontextUtils;

i)port 8avax"servlet"Servlet6e4uest; i)port 8avax"servlet"http"HttpServlet6e4uest;

public class Service:inder {

public static /pplication%ontext get%ontext#HttpServlet6e4uest http6e4uest$ { return Jeb/pplication%ontextUtils"get6e4uiredJeb/pplication%ontext# http6e4uest"getSession#$"getServlet%ontext#$$; 3 3

Hibernate 2art
Step 7- Create Table in ata !ase

C5'A%' %AB&' Stec"fa6S.Suser:testS H Suser:idS intH12I unsi ned +O% +U&& auto:incre$entD Suser:na$eS varc"arH(7I default +U&&D Sdept:na$eS varc"arH(7I default +U&&D C5*8A5B L'B HSuser:idSIIG

Step 8- user-hbm-xml whi"h maps to userDtest TA!$E

;<#$l version=>1.2> encodin =>U%,-?><@ ;ADOC%BC' "ibernate-$appin CUB&*C >-//Hibernate/Hibernate 8appin D%D//'+> >"ttpE//"ibernate.sourcefor e.net/"ibernate-$appin --.2.dtd>@ ;"ibernate-$appin @ ;class na$e=>co$.UserBean> table=>US'5:%'S%>@ ;id na$e=>user*d> colu$n=>US'5:*D> t4pe=>int>@ ; enerator class=>native>/@ ;/id@ ;propert4 na$e=>user+a$e> colu$n=>user:na$e>/@ ;propert4 na$e=>dept+a$e> colu$n=>dept:na$e>/@

;/class@ ;/"ibernate-$appin @

Step ;- (ser!ean-+ava whi"h maps to user-hbm-xml and userDtest TA!$E


package co);

public class UserBean { int userId; String user=a)e; String dept=a)e;

/** * 5return 6eturns the user=a)e" */ public String getUser=a)e#$ { return user=a)e; 3 /** * 5para) user=a)e -he user=a)e to set" */ public void setUser=a)e#String user=a)e$ { this"user=a)e ! user=a)e; 3 /** * 5return 6eturns the dept=a)e" */ public String getDept=a)e#$ { return dept=a)e; 3 /** * 5para) dept=a)e -he dept=a)e to set" */ public void setDept=a)e#String dept=a)e$ { this"dept=a)e ! dept=a)e; 3 /** * 5return 6eturns the userId" */ public int getUserId#$ { return userId; 3 /** * 5para) userId -he userId to set" */ public void setUserId#int userId$ { this"userId ! userId; 3 3

Step :- (ser AO-+ava whi"h is used to save user details into ata !ase
package co);

i)port org"hibernate"Session; i)port org"hibernate"Session:actor(;

i)port org"hibernate"-ransaction; i)port org"spring ra)e&ork"or)"hibernate"support"HibernateDaoSupport;

public class UserD/9 { private Session:actor( session:actor(; public void saveUser#UserBean user${ Session session ! getSession:actor(#$"openSession#$; tr( { -ransaction tx ! session"begin-ransaction#$; session"save#user$; tx"co))it#$; 3catch#'xception e${ e"printStack-race#$; 3 inall({ session"close#$; 3 3

/** * 5return 6eturns the session:actor(" */ public Session:actor( getSession:actor(#$ { return session:actor(; 3 /** * 5para) session:actor( -he session:actor( to set" */ public void setSession:actor(#Session:actor( session:actor($ { this"session:actor( ! session:actor(; 3 3

You might also like