Professional Documents
Culture Documents
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
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.
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@
//-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#$;
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
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
;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@
er=a)e$ {
"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.
"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 :- 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
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
>-//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 @
;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@
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
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
varchar7 varch
"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
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 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
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 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 ;- &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
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@
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
Sub,ueries
fro$ '$plo4ee as e !"ere e.na$e = so$e H
'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
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
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
;/class@ ;/"ibernate-$appin @
$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
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
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
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
"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
"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 @
;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#$;
"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
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 @
;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#$;
"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 @
;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#$;
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.
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@
;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
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
;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;
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
;<#$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 @
/** * 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);
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