Hibernate Tutorial Step by Step

download Hibernate Tutorial Step by Step

of 61

Transcript of Hibernate Tutorial Step by Step

  • 8/14/2019 Hibernate Tutorial Step by Step

    1/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 Setp with an web Appli!ation

    #irst Hibernate Appli"ationSimple 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 ttorial 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"tionalOne 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 ttorial in!ldes from !lase(Asso!iations and )oins( Aggregate fn!tions("he order by

    !lase("he grop by !lase(Sb*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

    http://www.techfaq360.com/tutorial.jsp?catId=7http://www.techfaq360.com/tutorial/hibernate_jdbc.jsphttp://www.techfaq360.com/tutorial/hibernate_setup.jsphttp://www.techfaq360.com/tutorial/firstHibernateApplication.jsphttp://www.techfaq360.com/tutorial/hibernatemapping.jsphttp://www.techfaq360.com/tutorial/hibernate_data_type.jsphttp://www.techfaq360.com/tutorial/one_to_many.jsphttp://www.techfaq360.com/tutorial/one_to_many_bi_directional.jsphttp://www.techfaq360.com/tutorial/many_to_many.jsphttp://www.techfaq360.com/tutorial/hql.jsphttp://www.techfaq360.com/tutorial/hql.jsphttp://www.techfaq360.com/tutorial/criteria.jsphttp://www.techfaq360.com/tutorial/criteriaquries.jsphttp://www.techfaq360.com/tutorial/criteriaquries.jsphttp://www.techfaq360.com/tutorial/hibernate_jdbc.jsphttp://www.techfaq360.com/tutorial/hibernate_setup.jsphttp://www.techfaq360.com/tutorial/firstHibernateApplication.jsphttp://www.techfaq360.com/tutorial/hibernatemapping.jsphttp://www.techfaq360.com/tutorial/hibernate_data_type.jsphttp://www.techfaq360.com/tutorial/one_to_many.jsphttp://www.techfaq360.com/tutorial/one_to_many_bi_directional.jsphttp://www.techfaq360.com/tutorial/many_to_many.jsphttp://www.techfaq360.com/tutorial/hql.jsphttp://www.techfaq360.com/tutorial/hql.jsphttp://www.techfaq360.com/tutorial/criteria.jsphttp://www.techfaq360.com/tutorial/criteriaquries.jsphttp://www.techfaq360.com/tutorial/criteriaquries.jsphttp://www.techfaq360.com/tutorial.jsp?catId=7
  • 8/14/2019 Hibernate Tutorial Step by Step

    2/61

    the reslts +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"rementallySample 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 ttorial gide yo how yo !an integrate Strts Spring Hibernate in a 5eb Appli!ation."his is simple appli!ation where ser form +67, as Strts 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

    http://www.techfaq360.com/tutorial/criteriaquriesandor.jsphttp://www.techfaq360.com/tutorial/generatorkexample.jsphttp://www.techfaq360.com/tutorial/versioncheck.jsphttp://www.techfaq360.com/tutorial/versioncheck.jsphttp://www.techfaq360.com/tutorial/versioncheck.jsphttp://www.techfaq360.com/tutorial/spring/struts_spring_hibernate.jsphttp://www.techfaq360.com/tutorial.jsp?catId=7http://www.techfaq360.com/tutorial/criteriaquriesandor.jsphttp://www.techfaq360.com/tutorial/generatorkexample.jsphttp://www.techfaq360.com/tutorial/versioncheck.jsphttp://www.techfaq360.com/tutorial/versioncheck.jsphttp://www.techfaq360.com/tutorial/versioncheck.jsphttp://www.techfaq360.com/tutorial/spring/struts_spring_hibernate.jsphttp://www.techfaq360.com/tutorial.jsp?catId=7
  • 8/14/2019 Hibernate Tutorial Step by Step

    3/61

    Hibernate Tutorial Step by Step -- Code Examples

    Advantage of Hibernate over JDBC

    Advantage are9, 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 mst be data base spe!ifi!.

    :, As Hibernate is set of Ob)e!ts ( yo don;t need to learn S%# langage.

  • 8/14/2019 Hibernate Tutorial Step by Step

    4/61

    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 confiuration 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

    -------------cp2-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-loin.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 webxml file

    "his servlet is only for load !onfigration files related to Hibernate and !reate Session 8a!tory

    on start p .

    Create Session #a"tory is very Expensive

  • 8/14/2019 Hibernate Tutorial Step by Step

    5/61

    Create Session 8a!tory is very Expensive so we added one servlet to !reate on server startp

    4nitiali9e Conne"tion pool on startup

    7nitialie Conne!tion pool on startp sing !=p.

    4nitiali9e log:+ "onfiguration

    7nitialie log>) !onfigration on startp.

    ;1.2> encodin=>*SO-??73-1>

    >"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%onig conig$ thro&s Servlet'xception {

    S(ste)"out"println#+n**** Initiali,ing Hibernate Init Servlet

    ********** +n$;

    super"init#conig$;

    //-his is or local properties"

    String cgDir ! D.++testpp++conig;

    logger"ino#conig dir.0cgDir$;

    initLog1ro#cgDir$;

    tr({

    HibernateUtil"appHo)e ! cgDir;

    HibernateUtil"init2onitor#$;

    http://java.sun.com/dtd/web-app_2_3.dtdhttp://java.sun.com/dtd/web-app_2_3.dtd
  • 8/14/2019 Hibernate Tutorial Step by Step

    6/61

    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(%onigurator"conigure#path0:ile"separator%har0log8"properties$;

    3catch#'xception ex${

    S(ste)"out"println#Log< can not be initiali,ed$;

    logger"ino#Log< can not be initiali,ed$;

    3

    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( ro) the deault

    coniguration iles

    public static void conigure#${

    tr( {

    String path>properties !

  • 8/14/2019 Hibernate Tutorial Step by Step

    7/61

    appHo)e0:ile"separator%har0hibernate"cg"x)l;

    %oniguration coniguration ! ne& %oniguration#$;

    coniguration"add:ile#path>properties$;

    session:actor(

    !coniguration"conigure#$"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$ conigure#$;

    return session:actor(;

    3

    public static Session getSession#${

    Session s ! #Session$ threadSession"get#$;// logger"debug#session0s$;

    i #s !! null$ {

    s ! getSession:actor(#$"openSession#$;

    threadSession"set#s$;

    // logger"debug#session ? @0s$;

    3

    return s;

    3

    3

    Step -//Hibernate/Hibernate Confiuration D%D .2//'+>

    >"ttpE//"ibernate.sourcefore.net/"ibernate-confiuration-.2.dtd>@

    ;"ibernate-confiuration@

    ;session-factor4@

    ;-- Database connection settins --@

    ;propert4

    na$e=>connection.driver:class>@co$.$4s6l.jdbc.Driver;/propert4@

    ;propert4

    na$e=>connection.url>@jdbcE$4s6lE//local"ostE20/tec"fa6db;/propert4

    @

    ;propert4 na$e=>connection.userna$e>@tec"fa6;/propert4@

    ;propert4 na$e=>connection.pass!ord>@tec"fa6;/propert4@

    http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd
  • 8/14/2019 Hibernate Tutorial Step by Step

    8/61

    ;-- JDBC connection pool use t"e built-inI --@

    ;propert4 na$e=>"ibernate.cp2.$in:sie>@1;/propert4@

    ;propert4 na$e=>"ibernate.cp2.$a#:sie>@(;/propert4@

    ;propert4 na$e=>"ibernate.cp2.ti$eout>@1?22;/propert4@

    ;propert4 na$e=>"ibernate.cp2.$a#:state$ents>@72;/propert4@

    ;-- 84S9& dialect//different for different Database --@;propert4

    na$e=>dialect>@or."ibernate.dialect.84S9&Dialect;/propert4@

    ;-- 'nable HibernateFs auto$atic session conte#t $anae$ent --@

    ;propert4 na$e=>current:session:conte#t:class>@t"read;/propert4@

    ;-- Disable t"e second-level cac"e --@

    ;propert4

    na$e=>cac"e.provider:class>@or."ibernate.cac"e.+oCac"erovider;/pro

    pert4@

    ;-- '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-confiuration@

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

    package beans;

    public class 9er {

    private long oerId;private String oer=a)e;

    /**

    * 5return 6eturns the oerId"

    */ public long get9erId#$ {

    return oerId;

    3

    /**

    * 5para) oerId -he oerId to set"

    */

    private void set9erId#long oerId$ {

    this"oerId ! oerId;

    3

    /** * 5return 6eturns the oer=a)e"

    */

    public String get9er=a)e#$ {

    return oer=a)e;

    3

    /**

    * 5para) oer=a)e -he oer=a)e to set"

  • 8/14/2019 Hibernate Tutorial Step by Step

    9/61

    */

    public void set9er=a)e#String oer=a)e$ {

    this"oer=a)e ! oer=a)e;

    3

    3

    Step > Offer+ava and O##E' TA!$E mapping in Offerhbmxml

    ;1.2>

    >"ttpE//"ibernate.sourcefore.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 offer:id nu$berG offer:na$e varc"ar IG

    "hen start the server.

  • 8/14/2019 Hibernate Tutorial Step by Step

    10/61

    na$e varc"ar

    IG

    // ,O5 O5AC&'

    create table '8&O''

    id nu$berG

    na$e varc"arIG

    Step 8 Create Emp+ava bean "lass

    Hibernate ses the 2lain Old Java Ob)e!ts +2OJOs, !lasses to map to the database table

    +Emp.)ava to E&2#O-//Hibernate/Hibernate 8appin D%D .2//'+>>"ttpE//"ibernate.sourcefore.net/"ibernate-$appin-.2.dtd>@

    ;"ibernate-$appin@

    ;class na$e=>'$p> table=>'8&O''>@

    ;id na$e=>id> colu$n=>id> t4pe=>lon>@

    ;enerator class=>incre$ent>/@ // %"is enerates t"e pri$ar4

    Ke4

    http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd
  • 8/14/2019 Hibernate Tutorial Step by Step

    11/61

    ;/id@

    ;propert4 na$e=>na$e> colu$n=>na$e>/@

    ;/class@

    ;/"ibernate-$appin@

    Step : add Emphbmxml into hibernate"fgxml

    Hibernate provided !onne!tion pooling sning !=p and transa!tion management . Hibernate

    ses the hibernate.!fg.xml to !reate the !onne!tion pool and setp re*ired environment

    ;

    >"ttpE//"ibernate.sourcefore.net/"ibernate-confiuration-.2.dtd>@

    ;"ibernate-confiuration@

    ;session-factor4@

    ;-- Database connection settins --@

    ;propert4

    na$e=>connection.driver:class>@co$.$4s6l.jdbc.Driver;/propert4@

    ;propert4

    na$e=>connection.url>@jdbcE$4s6lE//local"ostE20/tec"fa6db;/propert4

    @

    ;propert4 na$e=>connection.userna$e>@tec"fa6;/propert4@

    ;propert4 na$e=>connection.pass!ord>@tec"fa6;/propert4@

    ;-- JDBC connection pool use t"e built-inI --@

    ;propert4 na$e=>"ibernate.cp2.$in:sie>@1;/propert4@;propert4 na$e=>"ibernate.cp2.$a#:sie>@(;/propert4@

    ;propert4 na$e=>"ibernate.cp2.ti$eout>@1?22;/propert4@

    ;propert4 na$e=>"ibernate.cp2.$a#:state$ents>@72;/propert4@

    ;-- 84S9& dialect//different for different Database --@

    ;propert4

    na$e=>dialect>@or."ibernate.dialect.84S9&Dialect;/propert4@

    ;-- 'nable HibernateFs auto$atic session conte#t $anae$ent --@

    ;propert4 na$e=>current:session:conte#t:class>@t"read;/propert4@

    ;-- Disable t"e second-level cac"e --@

    ;propert4na$e=>cac"e.provider:class>@or."ibernate.cac"e.+oCac"erovider;/pro

    pert4@

    ;-- '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@

    http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd
  • 8/14/2019 Hibernate Tutorial Step by Step

    12/61

    ;/"ibernate-confiuration@

    Step

  • 8/14/2019 Hibernate Tutorial Step by Step

    13/61

    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 offer:id nu$berG offer:na$e varc"ar IG

    Step 8 Create Offer+ava bean "lass

    package beans;

    public class 9er {

    private long oerId;

    private String oer=a)e;

    /**

    * 5return 6eturns the oerId"

    */ public long get9erId#$ {

    return oerId;

    3

    /**

    * 5para) oerId -he oerId to set"

    */

    private void set9erId#long oerId$ {

    this"oerId ! oerId;

    3

    /** * 5return 6eturns the oer=a)e"

    */

    public String get9er=a)e#$ {

    return oer=a)e;

    3

    /**

    * 5para) oer=a)e -he oer=a)e to set"

    */

    public void set9er=a)e#String oer=a)e$ {

    this"oer=a)e ! oer=a)e;

    3

    3

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

    ;1.2>

  • 8/14/2019 Hibernate Tutorial Step by Step

    14/61

    >-//Hibernate/Hibernate 8appin D%D .2//'+>

    >"ttpE//"ibernate.sourcefore.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$ar4Ke4

    ;/id@

    ;propert4 na$e=>offer+a$e> colu$n=>offer:na$e>/@

    ;/class@

    ;/"ibernate-$appin@

    Step : add Offerhbmxml into hibernate"fgxml

    ;

    >"ttpE//"ibernate.sourcefore.net/"ibernate-confiuration-.2.dtd>@

    ;"ibernate-confiuration@

    ;session-factor4@

    ;-- Database connection settins --@

    ;propert4

    na$e=>connection.driver:class>@co$.$4s6l.jdbc.Driver;/propert4@

    ;propert4

    na$e=>connection.url>@jdbcE$4s6lE//local"ostE20/tec"fa6db;/propert4

    @;propert4 na$e=>connection.userna$e>@tec"fa6;/propert4@

    ;propert4 na$e=>connection.pass!ord>@tec"fa6;/propert4@

    ;-- JDBC connection pool use t"e built-inI --@

    ;propert4 na$e=>"ibernate.cp2.$in:sie>@1;/propert4@

    ;propert4 na$e=>"ibernate.cp2.$a#:sie>@(;/propert4@

    ;propert4 na$e=>"ibernate.cp2.ti$eout>@1?22;/propert4@

    ;propert4 na$e=>"ibernate.cp2.$a#:state$ents>@72;/propert4@

    ;-- 84S9& dialect//different for different Database --@

    ;propert4

    na$e=>dialect>@or."ibernate.dialect.84S9&Dialect;/propert4@;-- 'nable HibernateFs auto$atic session conte#t $anae$ent --@

    ;propert4 na$e=>current:session:conte#t:class>@t"read;/propert4@

    ;-- Disable t"e second-level cac"e --@

    ;propert4

    na$e=>cac"e.provider:class>@or."ibernate.cac"e.+oCac"erovider;/pro

    pert4@

    http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-configuration-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-mapping-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd
  • 8/14/2019 Hibernate Tutorial Step by Step

    15/61

    ;-- '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-confiuration@

    Hibernate Tutorial Step by Step -- Code Examples

    Hibernate Data Type-Java Data Type - S$# Data Type mapping

    deci)al =U2'6I%7 =U2B'

    6

    loat7 double loat7 double loat7 double

    8ava"lang"Boolean7boolean boolean boolean7 int

    8ava"lang"string string varchar7 varch

    arC

    Ger( long strings text %L9B7 -'-

    8ava"util"Date date7 ti)e7 ti)esta)p D-'7 -I2'7 -I

    2'S-21

    8ava"util"%alendar calendar7 calendar>date -I2'S-217 D-

    '

    8ava"util"Locale locale varchar7varcha

    rC

    8ava"util"-i)eone ti)e,one varchar7 varch

  • 8/14/2019 Hibernate Tutorial Step by Step

    16/61

    arC

    8ava"util %urrenc( %urrenc( varchar7 varch

    arC

    8ava"s4l"%lob clob %L9B

    8ava"s4l"Blob blob BL9B

    @

    ;"ibernate-$appin@

    http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd
  • 8/14/2019 Hibernate Tutorial Step by Step

    17/61

    ;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 storyhbmxml- 6hi"h maps to STO' TA!$E

    ;1.2>

    >"ttpE//"ibernate.sourcefore.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 "lass

    public class Jriter {

    private int id;

    private String na)e;

    private List stories;

    public void setId#int i$ {

    id ! i;

    3public int getId#$ {

    return id;

    3

    public void set=a)e#String n$ {

    na)e ! n;

    3

    public String get=a)e#$ {

    http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd
  • 8/14/2019 Hibernate Tutorial Step by Step

    18/61

    return na)e;

    3

    public void setStories#List l$ {

    stories ! l;

    3

    public List getStories#$ {return stories;

    3

    3

    Step -//Hibernate/Hibernate Confiuration D%D .2//'+>

    >"ttpE//"ibernate.sourcefore.net/"ibernate-confiuration-.2.dtd>@

    ;"ibernate-confiuration@

    ;session-factor4@

    ;-- Database connection settins --@

    ;propert4

    http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd
  • 8/14/2019 Hibernate Tutorial Step by Step

    19/61

    na$e=>connection.driver:class>@co$.$4s6l.jdbc.Driver;/propert4@

    ;propert4

    na$e=>connection.url>@jdbcE$4s6lE//local"ostE20/tec"fa6db;/propert4

    @

    ;propert4 na$e=>connection.userna$e>@tec"fa6;/propert4@

    ;propert4 na$e=>connection.pass!ord>@tec"fa6;/propert4@;-- JDBC connection pool use t"e built-inI --@

    ;propert4 na$e=>"ibernate.cp2.$in:sie>@1;/propert4@

    ;propert4 na$e=>"ibernate.cp2.$a#:sie>@(;/propert4@

    ;propert4 na$e=>"ibernate.cp2.ti$eout>@1?22;/propert4@

    ;propert4 na$e=>"ibernate.cp2.$a#:state$ents>@72;/propert4@

    ;-- 84S9& dialect//different for different Database --@

    ;propert4

    na$e=>dialect>@or."ibernate.dialect.84S9&Dialect;/propert4@

    ;-- 'nable HibernateFs auto$atic session conte#t $anae$ent --@

    ;propert4 na$e=>current:session:conte#t:class>@t"read;/propert4@;-- Disable t"e second-level cac"e --@

    ;propert4

    na$e=>cac"e.provider:class>@or."ibernate.cac"e.+oCac"erovider;/pro

    pert4@

    ;-- '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-confiuration@

    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$ {

  • 8/14/2019 Hibernate Tutorial Step by Step

    20/61

    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'@;"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>/@

    http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd
  • 8/14/2019 Hibernate Tutorial Step by Step

    21/61

    ;one-to-$an4 class=>Stor4>/@

    ;/list@

    ;propert4 na$e=>na$e> colu$n=>+A8'> t4pe=>strin>/@

    ;/class@

    ;/"ibernate-$appin@

    Step ; &apping storyhbmxml- 6hi"h maps to STO' TA!$E

    ;1.2>

    >"ttpE//"ibernate.sourcefore.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> la4=>false>/@

    ;/class@

    ;/"ibernate-$appin@

    Step : Create 6riter+ava bean "lass

    public 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#$ {

    http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd
  • 8/14/2019 Hibernate Tutorial Step by Step

    22/61

    return stories;

    3

    3

    Step "ttpE//"ibernate.sourcefore.net/"ibernate-confiuration-.2.dtd>@

    ;"ibernate-confiuration@

    ;session-factor4@

    ;-- Database connection settins --@

    ;propert4

    http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd
  • 8/14/2019 Hibernate Tutorial Step by Step

    23/61

    na$e=>connection.driver:class>@co$.$4s6l.jdbc.Driver;/propert4@

    ;propert4

    na$e=>connection.url>@jdbcE$4s6lE//local"ostE20/tec"fa6db;/propert4

    @

    ;propert4 na$e=>connection.userna$e>@tec"fa6;/propert4@

    ;propert4 na$e=>connection.pass!ord>@tec"fa6;/propert4@;-- JDBC connection pool use t"e built-inI --@

    ;propert4 na$e=>"ibernate.cp2.$in:sie>@1;/propert4@

    ;propert4 na$e=>"ibernate.cp2.$a#:sie>@(;/propert4@

    ;propert4 na$e=>"ibernate.cp2.ti$eout>@1?22;/propert4@

    ;propert4 na$e=>"ibernate.cp2.$a#:state$ents>@72;/propert4@

    ;-- 84S9& dialect//different for different Database --@

    ;propert4

    na$e=>dialect>@or."ibernate.dialect.84S9&Dialect;/propert4@

    ;-- 'nable HibernateFs auto$atic session conte#t $anae$ent --@

    ;propert4 na$e=>current:session:conte#t:class>@t"read;/propert4@;-- Disable t"e second-level cac"e --@

    ;propert4

    na$e=>cac"e.provider:class>@or."ibernate.cac"e.+oCac"erovider;/pro

    pert4@

    ;-- '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-confiuration@

    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 mltiple spea1ers. And OneSpea1er !an spea1 in mltiple Event. So this is many to many relation. "o maintain this relation

    we have to introd!e third "AB#E name E4E-"S2EAGE'S .

    Step 7 "reate a tables EBE0TS * S@EAE'S and EBE0TDS@EAE'S in your database

    create table 'M'+%S

    event:id nu$ber //5*8A5 L'

    event:na$e varc"ar

  • 8/14/2019 Hibernate Tutorial Step by Step

    24/61

    IG

    create table S'AL'5S

    speaKer:id nu$ber //5*8A5 L'

    speaKer:na$e varc"ar

    IG

    create table 'M'+%:S'AL'5S elt nu$ber//pri$ar4 Ke4 event:id nu$ber speaKer:id nu$ber

    IG

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

    ;1.2>

    >"ttpE//"ibernate.sourcefore.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>

    lent"=>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 spea3erhbmxml- 6hi"h maps to S@EAE'S TA!$E

    ;1.2>>"ttpE//"ibernate.sourcefore.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>

    http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-mapping-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-mapping-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd
  • 8/14/2019 Hibernate Tutorial Step by Step

    25/61

    t4pe=>strin> lent"=>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 "lass

    public 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

  • 8/14/2019 Hibernate Tutorial Step by Step

    26/61

    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 eventhbmxml and spea3erhbmxml into hibernate"fgxml

    ;

    >"ttpE//"ibernate.sourcefore.net/"ibernate-confiuration-.2.dtd>@

    ;"ibernate-confiuration@

    ;session-factor4@

    ;-- Database connection settins --@

    ;propert4

    na$e=>connection.driver:class>@co$.$4s6l.jdbc.Driver;/propert4@;propert4

    na$e=>connection.url>@jdbcE$4s6lE//local"ostE20/tec"fa6db;/propert4

    @

    ;propert4 na$e=>connection.userna$e>@tec"fa6;/propert4@

    ;propert4 na$e=>connection.pass!ord>@tec"fa6;/propert4@

    ;-- JDBC connection pool use t"e built-inI --@

    ;propert4 na$e=>"ibernate.cp2.$in:sie>@1;/propert4@

    ;propert4 na$e=>"ibernate.cp2.$a#:sie>@(;/propert4@

    ;propert4 na$e=>"ibernate.cp2.ti$eout>@1?22;/propert4@

    ;propert4 na$e=>"ibernate.cp2.$a#:state$ents>@72;/propert4@;-- 84S9& dialect//different for different Database --@

    ;propert4

    na$e=>dialect>@or."ibernate.dialect.84S9&Dialect;/propert4@

    ;-- 'nable HibernateFs auto$atic session conte#t $anae$ent --@

    ;propert4 na$e=>current:session:conte#t:class>@t"read;/propert4@

    ;-- Disable t"e second-level cac"e --@

    ;propert4

    http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd
  • 8/14/2019 Hibernate Tutorial Step by Step

    27/61

    na$e=>cac"e.provider:class>@or."ibernate.cac"e.+oCac"erovider;/pro

    pert4@

    ;-- '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-confiuration@

    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$#' Te Hibernate $uery #anguage%"e Hibernate 9uer4 &anuae is

    e#ecuted usin session.create9uer4I. %"is tutorial includes fro$

    clauseAssociations and joins Areate functions%"e order b4 clause%"e roup

    b4 clauseSub6ueries.

    The from "lause

    fro$ '$plo4ee // '$plo4ee is class na$e $apped to

    '8&O'' %AB&'

    or

    fro$ '$plo4ee as e

    or

    fro$ '$plo4ee e !"ere e.e$p*d = G

  • 8/14/2019 Hibernate Tutorial Step by Step

    28/61

    &ist e$p&ist = session.create9uer4>fro$ '$plo4ee>I.listIG

    Asso"iations and +oins

    fro$ '$plo4ee e !"ere e.scope8od,la = 1 and pc.isDeleted = 1

    &ist e$p&ist = session.create9uer4>fro$ '$plo4ee e !"ere

    e.scope8od,la = 1 and pc.isDeleted = 1>I.listIG

    Aggregate fun"tions

    select avcat.!ei"tI su$cat.!ei"tI $a#cat.!ei"tI

    countcatI fro$ Cat cat Scrollable5esults rs =

    session.create9uer4>select avcat.!ei"tI su$cat.!ei"tI$a#cat.!ei"tI countcatI fro$ Cat cat>I.scrollIG

    ifrs.ne#tIIN

    S4ste$.out.printlnrs.et2IIG

    S4ste$.out.printlnrs.et1IIG

    S4ste$.out.printlnrs.etIIG

    S4ste$.out.printlnrs.etIIG

    The order by "lause

    fro$ '$plo4ee e order b4 e.na$e desc

    &ist e$p&ist = session.create9uer4>fro$ '$plo4ee e order b4

    e.na$e desc>I.listIG

    asc or desc indicate ascendin or descendin order

    respectivel4.

    The group by "lause

    select e.dept su$e.salar4I counteI '$plo4ee e roup b4cat.dept

    Sub,ueries

    fro$ '$plo4ee as e

    !"ere e.na$e = so$e

  • 8/14/2019 Hibernate Tutorial Step by Step

    29/61

    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

    aainst a particular persistent class. %"e Session is a factor4 for Criteria instances.

    Criteria ) Sele"t from Employee

    Criteria crie$p = session.createCriteria'$plo4ee.classIG

    &ist e$plist = crie$p.listIG

    'estri"tions to narrow result set

    "he !lass org.hibernate.!riterion.'estri!tions sed to narrow reslt set.

    // S'&'C% P ,5O8 '8&O'' )H'5' AQ'=(G ----S9&

    CO88A+D

    criteria 6uer4 for above 6uer4 is E

    &ist e$p&ist =

    session.createCriteria'$plo4ee.classI.add 5estrictions.e6>a

    e> ne! *nteer(I I I.listIG// +ot '6ual in "ibernate criteria // S'&'C% P ,5O8 '8&O''

    )H'5' AQ' =(G ----S9& CO88A+D

    criteria 6uer4 for above 6uer4 is E

    &ist e$p&ist =

    session.createCriteria'$plo4ee.classI.add 5estrictions.ne>a

    e> ne! *nteer(I I I.listIG

    Ordering the results

    // S'&'C% P ,5O8 '8&O'' )H'5' AQ'=( O5D'5 B'8:+A8' D'SCG ----S9& CO88A+D

    criteria 6uer4 for above 6uer4 is E

    &ist e$p&ist = session.createCriteria'$plo4ee.classI.

    add 5estrictions.e6>ae> ne!

    *nteer(I I I.addOrder Order.desc>e$pna$e>I I.listIG

  • 8/14/2019 Hibernate Tutorial Step by Step

    30/61

    Asso"iations

    // S'&'C% e.na$e ,5O8 '8&O'' e 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.createCriteria'$plo4ee.classI.createAlias>address>>a

    dd>I. add 5estrictions.e6>add.countr4> >US> I I.listIG

    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 '8&O'' e )H'5' e.dept=F*%FG ----S9&

    CO88A+D

    criteria 6uer4 for above 6uer4 is E

    '$plo4ee e$p = ne! '$plo4eeIG

    cat.setDeptF*%FIG

    &ist e$plist = session.createCriteria'$plo4ee.classI

    .add '#a$ple.createe$pI I

    .listIG

    Hibernate Tutorial Step by Step -- Code Examples

    Criteria $ueries ' E*ual +e*, .ot E*ual+ne, #ess tan +lt, #ess tan

    or e*ual+le, greater tan +gt,greater tan or e*ual+ge, and %rdering te

    results%"e interface or."ibernate.Criteria represents a 6uer4 aainst a particular

    persistent class. %"e Session is a factor4 for Criteria instances. *n t"is section it

    s"o! "o! to create %AB&' and OJO Java class and 8appin !it" t"e 9uer4.

    Create TA!$E E&@$OEE

    Create %AB&' '8&O''

    id nu$berG

    na$e varc"arG

    ae nu$berG

    IG

  • 8/14/2019 Hibernate Tutorial Step by Step

    31/61

    Create Employee+ava bean "lass

    Hibernate ses the 2lain Old Java Ob)e!ts +2OJOs, !lasses to map to the database table+Emp.)ava to E&2#O

    >"ttpE//"ibernate.sourcefore.net/"ibernate-$appin-.2.dtd>@

    ;"ibernate-$appin@

    ;class na$e=>'$plo4ee> table=>'8&O''>@

    ;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=>ae> colu$n=>ae> t4pe=>int>/@

    http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd
  • 8/14/2019 Hibernate Tutorial Step by Step

    32/61

    ;/class@

    ;/"ibernate-$appin@

    E,ual .e,/

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

    // S'&'C% P ,5O8 '8&O'' )H'5' AQ'=(G ----S9&

    CO88A+D

    criteria 6uer4 for above 6uer4 is E

    &ist e$p&ist =

    session.createCriteria'$plo4ee.classI.add 5estrictions.e6>a

    e> ne! *nteer(I I I.listIG

    0otE,ual .ne/

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

    // S'&'C% P ,5O8 '8&O'' )H'5' AQ' =(G ----S9&

    CO88A+D

    // +ot '6ual in "ibernate criteria criteria 6uer4 for above 6uer4

    is E

    &ist e$p&ist =

    session.createCriteria'$plo4ee.classI.add 5estrictions.ne>a

    e> ne! *nteer(I I I.listIG

    $ess than .lt/

    #ess than +lt, 7s sed to !he!1 less than in the *ery.

    // S'&'C% P ,5O8 '8&O'' )H'5' AQ' ; (G ----S9&

    CO88A+D

    // +ot '6ual in "ibernate criteria criteria 6uer4 for above 6uer4

    is E

    &ist e$p&ist =

    session.createCriteria'$plo4ee.classI.add 5estrictions.lt>ae

    > ne! *nteer(I I I.listIG

    $ess than or e,ual.le/

  • 8/14/2019 Hibernate Tutorial Step by Step

    33/61

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

    // S'&'C% P ,5O8 '8&O'' )H'5' AQ' ;= (G ----S9&

    CO88A+D

    // +ot '6ual in "ibernate criteria criteria 6uer4 for above 6uer4

    is E&ist e$p&ist =

    session.createCriteria'$plo4ee.classI.add 5estrictions.le>ae

    > ne! *nteer(I I I.listIG

    Freater than .gt/

    Ireater than +gt, 7s sed to !he!1 greater than in the *ery.

    // S'&'C% P ,5O8 '8&O'' )H'5' AQ' @ (G ----S9&

    CO88A+D

    // +ot '6ual in "ibernate criteria criteria 6uer4 for above 6uer4

    is E

    &ist e$p&ist =

    session.createCriteria'$plo4ee.classI.add 5estrictions.t>a

    e> ne! *nteer(I I I.listIG

    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 '8&O'' )H'5' AQ' @= (G ----S9&

    CO88A+D

    // +ot '6ual in "ibernate criteria criteria 6uer4 for above 6uer4

    is E

    &ist e$p&ist =

    session.createCriteria'$plo4ee.classI.add 5estrictions.e>a

    e> ne! *nteer(I I I.listIG

    Ordering the results

    // S'&'C% P ,5O8 '8&O'' )H'5' AQ'=( O5D'5 B +A8'

    D'SCG ----S9& CO88A+D

    criteria 6uer4 for above 6uer4 is E

    &ist e$p&ist = session.createCriteria'$plo4ee.classI.

    add 5estrictions.e6>ae> ne!

  • 8/14/2019 Hibernate Tutorial Step by Step

    34/61

    *nteer(I I I.addOrder Order.desc>na$e>I I.listIG

    Hibernate Tutorial Step by Step -- Code Examples

    Criteria $ueries' And %) !onditions%"e interface or."ibernate.Criteria

    represents a 6uer4 aainst a particular persistent class. %"e Session is a factor4 for

    Criteria instances. *n t"is section it s"o! "o! to create %AB&' and OJO Java class

    and 8appin !it" t"e 9uer4.

    Create TA!$E E&@$OEE

    Create %AB&' '8&O''

    id nu$berG

    na$e varc"arG

    ae nu$berG

    IG

    Create Employee+ava bean "lass

    Hibernate ses the 2lain Old Java Ob)e!ts +2OJOs, !lasses to map to the database table+Emp.)ava to E&2#O

  • 8/14/2019 Hibernate Tutorial Step by Step

    35/61

    3

    public int getge#$ {

    return age;

    3

    private void setge#int age$ {

    this"age ! age;3

    3

    Employeehbmxml - This mapps E&@$OEE TA!$E and Emp+ava

    ;1.2>

    >"ttpE//"ibernate.sourcefore.net/"ibernate-$appin-.2.dtd>@;"ibernate-$appin@

    ;class na$e=>'$plo4ee> table=>'8&O''>@

    ;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=>ae> colu$n=>ae> t4pe=>int>/@

    ;/class@

    ;/"ibernate-$appin@

    And Condtion

    "his method retrns the !on)n!tions of two expressions. Both !onditions are ;tre; then it

    ex!tes the *ery otherwise not.

    // S'&'C% P ,5O8 '8&O'' )H'5' AQ'=( A+D AQ'=?G

    ----S9& CO88A+D

    criteria 6uer4 for above 6uer4 is E

    &ist e$p&ist = session.createCriteria'$plo4ee.classI.add 5estrictions.e6>ae> ne! *nteer(I I I

    .add 5estrictions.e6>ae> ne! *nteer?I I I

    .listIG

    O' Condtion

    http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd
  • 8/14/2019 Hibernate Tutorial Step by Step

    36/61

    "his method retrns the dis)!tion of two expressions. Any given !ondition is ;tre; then it

    exe!tes the *ery. 7n this ttorial( or is sed

    // S'&'C% P ,5O8 '8&O'' )H'5' AQ'=( O5 AQ'=?G

    ----S9& CO88A+D

    criteria 6uer4 for above 6uer4 is E&ist e$p&ist = session.createCriteria'$plo4ee.classI

    .add'#pression.or

    '#pression.e6>ae> ne! *nteer(I I I

    '#pression.e6>ae> ne! *nteer?I I II

    .listIG

    Hibernate Tutorial Step by Step -- Code ExamplesHibernate /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

    incrementgenerates 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 !lster. 8ollow the setps

    Step 7 "reate a table name E&@$OEE in your database

    // for 84S9&

    create table '8&O''

    id biint2I

    na$e varc"ar

    IG

    // ,O5 O5AC&'

    create table '8&O''

    id nu$berG

    na$e varc"ar

    IG

    Step 8 Create Emp+ava bean "lass

    Hibernate ses the 2lain Old Java Ob)e!ts +2OJOs, !lasses to map to the database table+Emp.)ava to E&2#O

  • 8/14/2019 Hibernate Tutorial Step by Step

    37/61

    public class ')p {

    private long id;

    private String na)e;

    public long getId#$ {

    return id;

    3private 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 ; Emphbmxml - This mapps E&@$OEE TA!$E and Emp+ava ) incrementfor

    the generator "lass

    ;1.2>

    >"ttpE//"ibernate.sourcefore.net/"ibernate-$appin-.2.dtd>@

    ;"ibernate-$appin@

    ;class na$e=>'$p> table=>'8&O''>@;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 Emphbmxml into hibernate"fgxml

    Hibernate provided !onne!tion pooling sning !=p and transa!tion management . Hibernate

    ses the hibernate.!fg.xml to !reate the !onne!tion pool and setp re*ired environment

    ;

    http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd
  • 8/14/2019 Hibernate Tutorial Step by Step

    38/61

    >"ttpE//"ibernate.sourcefore.net/"ibernate-confiuration-.2.dtd>@

    ;"ibernate-confiuration@

    ;session-factor4@

    ;-- Database connection settins --@

    ;propert4

    na$e=>connection.driver:class>@co$.$4s6l.jdbc.Driver;/propert4@;propert4

    na$e=>connection.url>@jdbcE$4s6lE//local"ostE20/tec"fa6db;/propert4

    @

    ;propert4 na$e=>connection.userna$e>@tec"fa6;/propert4@

    ;propert4 na$e=>connection.pass!ord>@tec"fa6;/propert4@

    ;-- JDBC connection pool use t"e built-inI --@

    ;propert4 na$e=>"ibernate.cp2.$in:sie>@1;/propert4@

    ;propert4 na$e=>"ibernate.cp2.$a#:sie>@(;/propert4@

    ;propert4 na$e=>"ibernate.cp2.ti$eout>@1?22;/propert4@

    ;propert4 na$e=>"ibernate.cp2.$a#:state$ents>@72;/propert4@;-- 84S9& dialect//different for different Database --@

    ;propert4

    na$e=>dialect>@or."ibernate.dialect.84S9&Dialect;/propert4@

    ;-- 'nable HibernateFs auto$atic session conte#t $anae$ent --@

    ;propert4 na$e=>current:session:conte#t:class>@t"read;/propert4@

    ;-- Disable t"e second-level cac"e --@

    ;propert4

    na$e=>cac"e.provider:class>@or."ibernate.cac"e.+oCac"erovider;/pro

    pert4@

    ;-- '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-confiuration@

    Step

  • 8/14/2019 Hibernate Tutorial Step by Step

    39/61

    Session session ! null;

    tr({ // -his step &ill read hibernate"cg"x)l

    Session:actor( session:actor( ! ne&

    %oniguration#$"conigure#$"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 Done 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${

    3inall({

    session"close#$;

    3

    3

    3

    Hibernate Tutorial Step by Step -- Code Examples

    2revent !on!urrent update in Hibernate

    "his ttorial resolve the isse of 6ser thin1 time + one ser edit the re!ord for pdate and

    thin1ing and !hanging vales ( same time other ser edit the same re!ord and pdate. then firstser pdate and :nd ser;s data is lost.,

  • 8/14/2019 Hibernate Tutorial Step by Step

    40/61

    data.

    8or example

    6ser A edit the row of the "AB#E for pdate + 7n the 6ser 7nterfa!e !hanging data $ "his is serthin1ing 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 nmber and mat!h with yor version nmber + onthe 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 method

    public 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;

    3public 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

    *D nu$ber //5*8A5 L'

    +A8' varc"ar

    version nu$ber

    IG

  • 8/14/2019 Hibernate Tutorial Step by Step

    41/61

    Step ; Add property in writerhbmxml and optimisti"-lo"3GversionG - 6hi"h maps to

    6'4TE' TA!$E

    ;1.2>>"ttpE//"ibernate.sourcefore.net/"ibernate-$appin-.2.dtd>@

    ;"ibernate-$appin@

    ;class na$e=>)riter> table=>)5*%'5> opti$istic-

    locK=>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 writerhbmxml into hibernate"fgxml

    ;

    >"ttpE//"ibernate.sourcefore.net/"ibernate-confiuration-.2.dtd>@

    ;"ibernate-confiuration@

    ;session-factor4@;-- Database connection settins --@

    ;propert4

    na$e=>connection.driver:class>@co$.$4s6l.jdbc.Driver;/propert4@

    ;propert4

    na$e=>connection.url>@jdbcE$4s6lE//local"ostE20/tec"fa6db;/propert4

    @

    ;propert4 na$e=>connection.userna$e>@tec"fa6;/propert4@

    ;propert4 na$e=>connection.pass!ord>@tec"fa6;/propert4@

    ;-- JDBC connection pool use t"e built-inI --@

    ;propert4 na$e=>"ibernate.cp2.$in:sie>@1;/propert4@;propert4 na$e=>"ibernate.cp2.$a#:sie>@(;/propert4@

    ;propert4 na$e=>"ibernate.cp2.ti$eout>@1?22;/propert4@

    ;propert4 na$e=>"ibernate.cp2.$a#:state$ents>@72;/propert4@

    ;-- 84S9& dialect//different for different Database --@

    ;propert4

    na$e=>dialect>@or."ibernate.dialect.84S9&Dialect;/propert4@

    ;-- 'nable HibernateFs auto$atic session conte#t $anae$ent --@

    http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-configuration-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-mapping-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd
  • 8/14/2019 Hibernate Tutorial Step by Step

    42/61

    ;propert4 na$e=>current:session:conte#t:class>@t"read;/propert4@

    ;-- Disable t"e second-level cac"e --@

    ;propert4

    na$e=>cac"e.provider:class>@or."ibernate.cac"e.+oCac"erovider;/pro

    pert4@

    ;-- '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-confiuration@

    Step

  • 8/14/2019 Hibernate Tutorial Step by Step

    43/61

    2revent !on!urrent update in Hibernate

    "his ttorial resolve the isse of 6ser thin1 time + one ser edit the re!ord for pdate andthin1ing and !hanging vales ( same time other ser edit the same re!ord and pdate. then first

    ser pdate and :nd ser;s data is lost.,

  • 8/14/2019 Hibernate Tutorial Step by Step

    44/61

    create table )5*%'5

    *D nu$ber //5*8A5 L'

    +A8' varc"ar

    version nu$ber

    IG

    Step ; Add property in writerhbmxml and optimisti"-lo"3GversionG - 6hi"h maps to

    6'4TE' TA!$E

    ;1.2>

    >"ttpE//"ibernate.sourcefore.net/"ibernate-$appin-.2.dtd>@

    ;"ibernate-$appin@

    ;class na$e=>)riter> table=>)5*%'5> opti$istic-

    locK=>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 writerhbmxml into hibernate"fgxml

    ;

    >"ttpE//"ibernate.sourcefore.net/"ibernate-confiuration-.2.dtd>@

    ;"ibernate-confiuration@

    ;session-factor4@

    ;-- Database connection settins --@

    ;propert4

    na$e=>connection.driver:class>@co$.$4s6l.jdbc.Driver;/propert4@;propert4

    na$e=>connection.url>@jdbcE$4s6lE//local"ostE20/tec"fa6db;/propert4

    @

    ;propert4 na$e=>connection.userna$e>@tec"fa6;/propert4@

    ;propert4 na$e=>connection.pass!ord>@tec"fa6;/propert4@

    ;-- JDBC connection pool use t"e built-inI --@

    ;propert4 na$e=>"ibernate.cp2.$in:sie>@1;/propert4@

    http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-configuration-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-mapping-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd
  • 8/14/2019 Hibernate Tutorial Step by Step

    45/61

    ;propert4 na$e=>"ibernate.cp2.$a#:sie>@(;/propert4@

    ;propert4 na$e=>"ibernate.cp2.ti$eout>@1?22;/propert4@

    ;propert4 na$e=>"ibernate.cp2.$a#:state$ents>@72;/propert4@

    ;-- 84S9& dialect//different for different Database --@

    ;propert4

    na$e=>dialect>@or."ibernate.dialect.84S9&Dialect;/propert4@;-- 'nable HibernateFs auto$atic session conte#t $anae$ent --@

    ;propert4 na$e=>current:session:conte#t:class>@t"read;/propert4@

    ;-- Disable t"e second-level cac"e --@

    ;propert4

    na$e=>cac"e.provider:class>@or."ibernate.cac"e.+oCac"erovider;/pro

    pert4@

    ;-- '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-confiuration@

    Step

  • 8/14/2019 Hibernate Tutorial Step by Step

    46/61

    Hibernate Tutorial Step by Step -- Code Examples

    2revent !on!urrent update in Hibernate

    "his ttorial resolve the isse of 6ser thin1 time + one ser edit the re!ord for pdate andthin1ing and !hanging vales ( same time other ser edit the same re!ord and pdate. then firstser pdate and :nd ser;s data is lost.,

  • 8/14/2019 Hibernate Tutorial Step by Step

    47/61

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

    create table )5*%'5

    *D nu$ber //5*8A5 L'

    +A8' varc"ar

    version nu$berIG

    Step ; Add property in writerhbmxml and optimisti"-lo"3GversionG - 6hi"h maps to

    6'4TE' TA!$E

    ;1.2>

    >"ttpE//"ibernate.sourcefore.net/"ibernate-$appin-.2.dtd>@

    ;"ibernate-$appin@

    ;class na$e=>)riter> table=>)5*%'5> opti$istic-

    locK=>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 writerhbmxml into hibernate"fgxml

    ;

    >"ttpE//"ibernate.sourcefore.net/"ibernate-confiuration-.2.dtd>@

    ;"ibernate-confiuration@

    ;session-factor4@

    ;-- Database connection settins --@

    ;propert4

    na$e=>connection.driver:class>@co$.$4s6l.jdbc.Driver;/propert4@

    ;propert4

    na$e=>connection.url>@jdbcE$4s6lE//local"ostE20/tec"fa6db;/propert4

    @

    ;propert4 na$e=>connection.userna$e>@tec"fa6;/propert4@

    ;propert4 na$e=>connection.pass!ord>@tec"fa6;/propert4@

    http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-configuration-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-mapping-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd
  • 8/14/2019 Hibernate Tutorial Step by Step

    48/61

    ;-- JDBC connection pool use t"e built-inI --@

    ;propert4 na$e=>"ibernate.cp2.$in:sie>@1;/propert4@

    ;propert4 na$e=>"ibernate.cp2.$a#:sie>@(;/propert4@

    ;propert4 na$e=>"ibernate.cp2.ti$eout>@1?22;/propert4@

    ;propert4 na$e=>"ibernate.cp2.$a#:state$ents>@72;/propert4@

    ;-- 84S9& dialect//different for different Database --@;propert4

    na$e=>dialect>@or."ibernate.dialect.84S9&Dialect;/propert4@

    ;-- 'nable HibernateFs auto$atic session conte#t $anae$ent --@

    ;propert4 na$e=>current:session:conte#t:class>@t"read;/propert4@

    ;-- Disable t"e second-level cac"e --@

    ;propert4

    na$e=>cac"e.provider:class>@or."ibernate.cac"e.+oCac"erovider;/pro

    pert4@

    ;-- '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-confiuration@

    Step

  • 8/14/2019 Hibernate Tutorial Step by Step

    49/61

    3ntegrate Struts Spring Hibernate 4eb Appli!ation

    "his ttorial gide yo to 7ntegrate Strts Spring Hibernate in a web appli!ation.

    Strts 4iew +6ser 7nterfa!e,Spring Servi!e #ayer

    Hibernate DAO layer

    Here is the steps for 7ntegration Strts Spring Hibernate 5eb Appli!ation

    ou "an download the "ode with 9ip strutsspringhibernate9ipCode is ready+ust

    download and run in tom"at Cli"3 donate button

    Steps to run t"e do!nloded code E

    step 1. unip t"e do!nloaded ip 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

    http://www.techfaq360.com/tutorial/spring/strutsspringhibernate.ziphttp://localhost:8080/strutsspringhibernate/userForm.dohttp://www.techfaq360.com/tutorial/spring/strutsspringhibernate.ziphttp://localhost:8080/strutsspringhibernate/userForm.do
  • 8/14/2019 Hibernate Tutorial Step by Step

    50/61

    step >. Enter 6ser -ame and Department and sbmit the save btton.

    Here is te !ode Explanation

    Struts 2art

    Step 7 Add A"tionServlet in webxml

    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 .

  • 8/14/2019 Hibernate Tutorial Step by Step

    51/61

    "irst Tas1 by A!tionServlet '%"e ActionServlet taKes t"e Struts Confi file na$e

    as an init-para$.

    At startup in t"e initI $et"od 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$.doin t"e bro!ser U5& bar t"eU5& !ill be intercepted and processed b4 t"e ActionServlet since t"e U5& "as a

    pattern P.do !it" a suffi# of >do>. Because servlet-$appin is

    ;servlet-$appin@

    ;servlet-na$e@action;/servlet-na$e@

    ;[email protected];/url-pattern@

    ;/servlet-$appin@

    Tird Tas1 by A!tionServlet '%"en ActionServlet deleates t"e re6uest "andlin

    to anot"er class called )e*uest2ro!essorb4 invoKin its processI $et"od.

    ;servlet@

    ;servlet-na$e@action;/servlet-na$e@

    ;[email protected]"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@

    ;[email protected];/url-pattern@;/servlet-$appin@

    Step 8 add A"tion&apping in struts-"onfigxml

    httpKKlo!alhost9KstrtsspringhibernateKser8orm.do!all to K)spKser8orm.)sp )sp.

    ;1.2> encodin=>*SO-??73-1>

    >"ttpE//jaKarta.apac"e.or/struts/dtds/struts-confi:1:.dtd>@

    ;struts-confi@

    ;for$-beans@

    http://localhost:8081/strutsspringhibernate/userForm.dohttp://localhost:8081/strutsspringhibernate/userForm.dohttp://jakarta.apache.org/struts/dtds/struts-config_1_2.dtdhttp://localhost:8081/strutsspringhibernate/userForm.dohttp://localhost:8081/strutsspringhibernate/userForm.dohttp://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd
  • 8/14/2019 Hibernate Tutorial Step by Step

    52/61

    ;for$-bean na$e=>User,or$>

    t4pe=>co$.User,or$>@

    ;/for$-bean@

    ;/for$-beans@

    ;action-$appins@

    ;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=>/paes/*nput.jsp>@

    ;for!ard na$e=>success> pat"=>/jsp/success.jsp>/@

    ;/action@

    ;/action-$appins@

    ;/struts-confi@

    Enter sername and deptname and !li!1 the Save btton.

    Save btton !alls Ksave6ser.do ( save6ser.do !alls !om.6serSaveA!tion based on above!onfigration in strts$!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

    M5 taglib uri!/J'BI=:/strutsht)l"tld preix!ht)lMN

    M5 taglib uri!/J'BI=:/strutsbean"tld preix!beanMN

    ht)l.or) action!/saveUser"do )ethod!postN

    User =a)e . ht)l.text propert(!user=a)e si,e!OF

    )axlength!?CF/N brN

    Depart)ent . ht)l.text propert(!dept=a)e si,e!OF

    )axlength!?CF/N brN

  • 8/14/2019 Hibernate Tutorial Step by Step

    53/61

    ht)l.sub)itNSave/ht)l.sub)itN /ht)l.or)N

    success.jsp

    ;"@User Data saved ;/"@

    !om5(serSaveA!tion56ava

    UserSaveAction et t"e user entered infor$ation 5e6uestrocessor set t"e user

    entered data into t"e User,or$I. Qet t"e service fro$ applicationConte#t.#$l usin

    UserService userservice = UserServiceI Service,inder.etConte#tre6uestI

    .etBean>userservice>IG

    *n t"e Action class just et t"e data fro$ User,or$ and call to

    userservice.saveUseruserbeanIG

    package co);

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

    i)port 8avax"servlet"http"HttpServlet6esponse;

    i)port org"apache"struts"action"ction;

    i)port org"apache"struts"action"ction:or);

    i)port org"apache"struts"action"ction:or&ard;

    i)port org"apache"struts"action"ction2apping;

    public class UserSavection 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$;

  • 8/14/2019 Hibernate Tutorial Step by Step

    54/61

    3

    3

    !om5(ser"orm56ava

    User,or$ is t"e ,or$ !"ic" contain t"e entered user infor$ation.5e6uestrocessor 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

  • 8/14/2019 Hibernate Tutorial Step by Step

    55/61

    Step 7 Add Context$oaderServlet in webxml

    ContextLoaderServlet

    Conte#t&oaderServlet reister an pplication%ontextusin t"e t"e belo!

    confiuration in !eb.#$l file.ou can et an4 service Defind in applicationConte#t.#$lI usin

    re6uest.etSessionI.etServletConte#tI.etBean>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@

    ;servlet-

    [email protected]$e!orK.!eb.conte#t.Conte#t&oaderServlet;/servlet-

    class@

    ;load-on-startup@1;/load-on-startup@

    ;/servlet@

    Step 8 appli"ationContextxml

    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.

    ;1.2> encodin=>U%,-?>

  • 8/14/2019 Hibernate Tutorial Step by Step

    56/61

    na$e=>url>@;value@jdbcE$4s6lE//local"ostE20/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.sprinfra$e!orK.or$."ibernate.&ocalSession,actor4Bean>@

    ;propert4 na$e=>dataSource>@;ref

    bean=>$4DataSource>/@;/propert4@

    ;propert4 na$e=>$appin5esources>@

    ;list@

    ;value@/co$/user."b$.#$l;/value@

    ;/list@

    ;/propert4@

    ;propert4 na$e=>"ibernateroperties>@;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 UserD9 userdao;

    public void saveUser#UserBean user${

    getUserdao#$"saveUser#user$;

  • 8/14/2019 Hibernate Tutorial Step by Step

    57/61

    3

    /**

    * 5return 6eturns the userdao"

    */

    public UserD9 getUserdao#$ {return userdao;

    3

    /**

    * 5para) userdao -he userdao to set"

    */

    public void setUserdao#UserD9 userdao$ {

    this"userdao ! userdao;

    3

    3

    !om5Servi!e"inder56ava

    package co);

    i)port org"springra)e&ork"context"pplication%ontext;

    i)port

    org"springra)e&ork"&eb"context"support"Jebpplication%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 Jebpplication%ontextUtils"get6e4uiredJebpplication%ontext#

    http6e4uest"getSession#$"getServlet%ontext#$$;

    33

    Hibernate 2art

    Step 7 Create Table in ata !ase

  • 8/14/2019 Hibernate Tutorial Step by Step

    58/61

    C5'A%' %AB&' tec"fa6.user:test

    user:id int12I unsined +O% +U&& auto:incre$ent

    user:na$e varc"ar(7I default +U&&

    dept:na$e varc"ar(7I default +U&&

    5*8A5 L' user:idIIG

    Step 8 userhbmxml whi"h maps to userDtest TA!$E

    ;1.2> encodin=>U%,-?>

    >"ttpE//"ibernate.sourcefore.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 userhbmxml and userDtest TA!$E

    package co);

    public class UserBean {

    int userId;

    String user=a)e;

    String dept=a)e;

    http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtdhttp://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd
  • 8/14/2019 Hibernate Tutorial Step by Step

    59/61

    /**

    * 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 : (serAO+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(;

  • 8/14/2019 Hibernate Tutorial Step by Step

    60/61

    i)port org"hibernate"-ransaction;

    i)port

    org"springra)e&ork"or)"hibernate"support"HibernateDaoSupport;

    public class UserD9 {

    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#$;3inall({

    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

  • 8/14/2019 Hibernate Tutorial Step by Step

    61/61