You are on page 1of 65

http://java.garnaik.com Version 1.

HIBERNA E IN ERVIE! "#E$ I%N$& 'AR ( II ": !hat are core inter)aces )or Hi*ernate )rame+ork, A: Most Hibernate-related application code primarily interacts with four interfaces provided by Hibernate Core: org.hibernate.Configuration org.hibernate.Session org.hibernate.SessionFactory org.hibernate.Criteria org.hibernate. uery !he configuration interface is used to load the hibernate configuration. !he Session is a persistence manager that manages operation li"e storing and retrieving ob#ects. $nstances of Session are ine%pensive to create and destroy. !hey are not thread safe. !he application obtains Session instances from a SessionFactory. SessionFactory instances are not lightweight and typically one instance is created for the whole application. $f the application accesses multiple databases& it needs one per database. !he Criteria provides a provision for conditional search over the resultset.'ne can retrieve entities by composing criterion ob#ects. !he Session is a factory for Criteria. Criterion instances are usually obtained via the factory methods on (estrictions. uery represents ob#ect oriented representation of a Hibernate )uery. A uery instance is obtained by calling Session.create uery*+. ": -i))erence *et+een session.save./ & session.save%r#p0ate./ an0 session.persist./, A: session.save*+ : Save does an insert and will fail if the primary "ey is already persistent. session.save'r,pdate*+ : save'r,pdate does a select first to determine if it needs to do an insert or an update. $nsert data if primary "ey not e%ist otherwise update data. session.persist*+ : -oes the same li"e session.save*+. .ut session.save*+ return Seriali/able ob#ect but session.persist*+ return void. session.save*+ returns the generated identifier *Seriali/able ob#ect+ and session.persist*+ doesn0t. For 1%ample :

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

if you do :System.out.println*session.save*)uestion++2 !his will print the generated primary "ey. if you do :System.out.println*session.persist*)uestion++2 Compile time error because session.persist*+ return void. ": !hat is the 0i))erence *et+een hi*ernate an0 j0*c , A: !here are so many 3+ Hibernate is data base independent& your code will wor" for all '(AC41&MyS 4 &S 4Server etc. $n case of 5-.C )uery must be data base specific. 6+ As Hibernate is set of 'b#ects & you don7t need to learn S 4 language. 8ou can treat !A.41 as a 'b#ect . 'nly 5ava "nowledge is need. $n case of 5-.C you need to learn S 4. 9+ -on7t need uery tuning in case of Hibernate. $f you use Criteria uires in Hibernate then hibernate automatically tuned your )uery and return best result with performance. $n case of 5-.C you need to tune your )ueries. :+ 8ou will get benefit of Cache. Hibernate support two level of cache. First level and 6nd level. So you can store your data into Cache for better performance. $n case of 5-.C you need to implement your #ava cache . ;+ Hibernate supports status. uery cache and $t will provide the statistics about your )uery and database

5-.C <ot provides any statistics. =+ -evelopment fast in case of Hibernate because you don7t need to write )ueries >+ <o need to create any connection pool in case of Hibernate. 8ou can use c9p?. $n case of 5-.C you need to write your own connection pool @+ $n the %ml file you can see all the relations between tables in case of Hibernate. 1asy readability. A+ 8ou can load your ob#ects on start up using la/yBfalse in case of Hibernate.

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

5-.C -on7t have such support. 3? + Hibernate Supports automatic versioning of rows but 5-.C <ot. ": !hat is 1a23 )etching in Hi*ernate, !ith E4amp1e. A: 4a/y fetching decides whether to load child ob#ects while loading the Carent 'b#ect. 8ou need to do this setting respective hibernate mapping file of the parent class. 4a/y B true *means not to load child+ .y default the la/y loading of the child ob#ects is true. !his ma"e sure that the child ob#ects are not loaded unless they are e%plicitly invo"ed in the application by calling getChild*+ method on parent.$n this case hibernate issues a fresh database call to load the child when getChild*+ is actully called on the Carent ob#ect. .ut in some cases you do need to load the child ob#ects when parent is loaded. 5ust ma"e the la/yBfalse and hibernate will load the child when parent is loaded from the database. 1%ample : $f you have a !A.41 7 1MC4'811 mapped to 1mployee ob#ect and contains set of Address ob#ects. Carent Class : 1mployee class Child class : Address Class public class 1mployee D private Set address B new HashSet*+2 EE contains set of child Address ob#ects public Set getAddress *+ D return address2 F public void setAddresss*Set address+ D this. address B address2 F F $n the 1mployee.hbm.%ml file Gset nameBHaddressH inverseBHtrueH cascadeBHdeleteH la/yBHfalseHI

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

G"ey columnBHaJidH EI Gone-to-many classBHbeans AddressHEI GEsetI $n the above configuration. $f la/yBHfalseH : - when you load the 1mployee ob#ect that time child ob#ect Adress is also loaded and set to setAddresss*+ method. $f you call employee.getAdress*+ then loaded data returns.<o fresh database call. $f la/yBHtrueH :- !his the default configuration. $f you don7t mention then hibernate consider la/yBtrue. when you load the 1mployee ob#ect that time child ob#ect Adress is not loaded. 8ou need e%tra call to data base to get address ob#ects. $f you call employee.getAdress*+ then that time database )uery fires and return results. Fresh database call. ": +hat is the a0vantage o) Hi*ernate over j0*c, A: !here are so many 3+ Hibernate is data base independent& your code will wor" for all '(AC41&MyS 4 &S 4Server etc. $n case of 5-.C )uery must be data base specific. 6+ As Hibernate is set of 'b#ects & you don7t need to learn S 4 language. 8ou can treat !A.41 as a 'b#ect . 'nly 5ava "nowledge is need. $n case of 5-.C you need to learn S 4. 9+ -ont need uery tuning in case of Hibernate. $f you use Criteria uires in Hibernate then hibernate automatically tuned your )uery and return best result with performance. $n case of 5-.C you need to tune your )ueries. :+ 8ou will get benefit of Cache. Hibernate support two level of cache. First level and 6nd level. So you can store your data into Cache for better performance. $n case of 5-.C you need to implement your #ava cache . ;+ Hibernate supports status. uery cache and $t will provide the statistics about your )uery and database

5-.C <ot provides any statistics.

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

=+ >+ @+

-evelopment fast in case of Hibernate because you dont need to write )ueries <o need to create any connection pool in case of Hibernate. 8ou can use c9p?. $n the %ml file you can see all the relations between tables in case of Hibernate. 1asy readability.

$n case of 5-.C you need to write your own connection pool A+ 8ou can load your ob#ects on start up using la/yBfalse in case of Hibernate. 5-.C -ont have such support. 3? + Hibernate Supports automatic versioning of rows but 5-.C <ot. ": !hat is c5p0, Ho+ o con)ig6re the 75'0 connection poo1, A: c9p? is an easy-to-use library for augmenting traditional *-riverManager-based+ 5-.C drivers with 5<-$-bindable -ataSources& including -ataSources that implement Connection and Statement Cooling& as described by the #dbc9 spec and #dbc6 std e%tension. $n simple you can say c9p? is an open source database connection pool used in hivernate. Configuration: Ke need to add the library C9C? #ar to our application lib. then we have to configure it in our hibernate configuration file. Here is a sample of C9C? configuration. !his is an e%tract of hibernate.cfg.%ml: GL-- configuration pool via c9p?--I Gproperty nameBHc9p?.ac)uireJincrementHI3GEpropertyI Gproperty nameBHc9p?.idleJtestJperiodHI3??GEpropertyI GL-- seconds --I Gproperty nameBHc9p?.ma%Jsi/eHI3??GEpropertyI Gproperty nameBHc9p?.ma%JstatementsHI?GEpropertyI Gproperty nameBHc9p?.minJsi/eHI3?GEpropertyI Gproperty nameBHc9p?.timeoutHI3??GEpropertyI GL-- seconds --I GL-- -1C(1CA!1- very e%pensive property nameBHc9p?.validateI--I 8ou also can set e%tra c9p? properties using c9p?.properties. Cut this file in the classpath *K1.$<FEclasses for e%ample+& but be careful& the previous values will be overridden by Hibernate whether set or not *see below for more details+. For more information on C9C? configuration& please have a loo" at http:EEsourceforge.netEpro#ectsEc9p? and un/ip the download& there is a doc folder where you0ll find everything you need. read more : http:EEwww.hibernate.orgE63:.html

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

": !hat is 0irt3 checking in Hi*ernate, A: Hibernate automatically detects ob#ect state changes in order to synchroni/e the updated state with the database& this is called dirty chec"ing. An important note here is& Hibernate will compare ob#ects by value& e%cept for Collections& which are compared by identity. For this reason you should return e%actly the same collection instance as Hibernate passed to the setter method to prevent unnecessary database updates. ": !hat are 0i))erent )etch strategies Hi*ernate have, A: A fetching strategy in Hibernate is used for retrieving associated ob#ects if the application needs to navigate the asociation. !hey may be declared in the 'E( mapping metadata& or over-ridden by a particular H 4 or Criteria )uery. Hibernate9 defines the following fetching strategies: 8oin )etching ( Hibernate retrieves the associated instance or collection in the same S141C!& using an ',!1( 5'$<. $e1ect )etching ( a second S141C! is used to retrieve the associated entity or collection. ,nless you e%plicitly disable la/y fetching by specifying la/yBHfalseH& this second select will only be e%ecuted when you actually access the association. $6*se1ect )etching ( a second S141C! is used to retrieve the associated collections for all entities retrieved in a previous )uery or fetch. ,nless you e%plicitly disable la/y fetching by specifying la/yBHfalseH& this second select will only be e%ecuted when you actually access the association. Batch )etching ( an optimi/ation strategy for select fetching - Hibernate retrieves a batch of entity instances or collections in a single S141C!& by specifying a list of primary "eys or foreign "eys. Hibernate also distinguishes between: Imme0iate )etching ( an association& collection or attribute is fetched immediately& when the owner is loaded. 9a23 co11ection )etching ( a collection is fetched when the application invo"es an operation upon that collection. *!his is the default for collections.+ :E4tra(1a23: co11ection )etching ( individual elements of the collection are accessed from the database as needed. Hibernate tries not to fetch the whole collection into memory unless absolutely needed *suitable for very large collections+ 'ro43 )etching ( a single-valued association is fetched when a method other than the identifier getter is invo"ed upon the associated ob#ect. :No(pro43: )etching ( a single-valued association is fetched when the instance variable is accessed. Compared to pro%y fetching& this approach is less la/y *the association is fetched even when only the

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

identifier is accessed+ but more transparent& since no pro%y is visible to the application. !his approach re)uires buildtime bytecode instrumentation and is rarely necessary. 9a23 attri*6te )etching ( an attribute or single valued association is fetched when the instance variable is accessed. !his approach re)uires buildtime bytecode instrumentation and is rarely necessary. Ke use fetch to tune performance. Ke may use la/y to define a contract for what data is always available in any detached instance of a particular class. ": E4p1ain 0i))erent inheritance mapping mo0e1s in Hi*ernate, A: !here can be three "inds of inheritance mapping in hibernate 3. !able per concrete class with unions 6. !able per class hierarchy 9. !able per subclass 1%ample: Ke can ta"e an e%ample of three 5ava classes li"e Mehicle& which is an abstract class and two subclasses of Mehicle as Car and ,tilityMan. 3. !able per concrete class with unions& $n this scenario there will be 6 tables !ables: Car& ,tilityMan& here in this case all common attributes will be duplicated. 6. !able per class hierarchy Single !able can be mapped to a class hierarchy !here will be only one table in database named 0Mehicle0 which will represent all attributes re)uired for all three classes. Here it is be ta"en care of that discriminating columns to differentiate between Car and ,tilityMan 9. !able per subclass Simply there will be three tables representing Mehicle& Car and ,tilityMan. ": Ho+ to Integrate $tr6ts1.1 $pring an0 Hi*ernate , A: $tep 1: $n the struts-config.%ml add plugin

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

Gplug-in class<ameBHorg.springframewor".web.struts.Conte%t4oaderClug$nHI Gset-property propertyBHconte%tConfig4ocationH valueBHEK1.-$<FEapplicationConte%t.%mlHEI GEplug-inI $tep ;: $n the applicationConte%t.%ml file Configure datasourse Gbean idBHdataSourceH classBHorg.springframewor".#dbc.datasource.-riverManager-ataSourceHI Gproperty nameBHdriverClass<ameHIGvalueIoracle.#dbc.driver.'racle-riverGEvalueI GEpropertyI Gproperty nameBHurlHIGvalueI#dbc:oracle:thin:N3?.3?.?3.6::3;:3:ebi/dGEvalueI GEpropertyI Gproperty nameBHusernameHIGvalueIsaGEvalueIGEpropertyI Gproperty nameBHpasswordHIGvalueIGEvalueIGEpropertyI GEbeanI $tep 5. Configure SessionFactory GL-- Hibernate SessionFactory --I Gbean idBHsessionFactoryH classBHorg.springframewor".orm.hibernate.4ocalSessionFactory.eanHI Gproperty nameBHdataSourceHIGref localBHdataSourceHEIGEpropertyI Gproperty nameBHmapping(esourcesHI GlistI GvalueIcomEtestEdb%mlE,ser.hbm.%mlGEvalueI GElistI GEpropertyI Gproperty nameBHhibernateCropertiesHI

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

GpropsI Gprop "eyBHhibernate.dialectHInet.sf.hibernate.dialect.'racle-ialect GEpropI GEpropsI GEpropertyI GEbeanI $tep <. Configure ,ser.hbm.%ml Ghibernate-mappingI Gclass nameBHcom.garnai".model.,serH tableBHappJuserHI Gid nameBHidH columnBHidH I Ggenerator classBHincrementHEI GEidI Gproperty nameBHfirst<ameH columnBHfirstJnameH not-nullBHtrueHEI Gproperty nameBHlast<ameH columnBHlastJnameH not-nullBHtrueHEI GEclassI GEhibernate-mappingI $tep =. $n the applicationConte%t.%ml 7 configure for -A' Gbean idBHuser-A'H classBHcom.garnai".dao.hibernate.,ser-A'HibernateHI Gproperty nameBHsessionFactoryHIGref localBHsessionFactoryHEIGEpropertyI GEbeanI

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

$tep >. -A' Class public class ,ser-A'Hibernate e%tends Hibernate-aoSupport implements ,ser-A' D private static 4og log B 4ogFactory.get4og*,ser-A'Hibernate.class+2 public 4ist get,sers*+ D return getHibernate!emplate*+.find*Hfrom ,serH+2 F public ,ser get,ser*4ong id+ D return *,ser+ getHibernate!emplate*+.get*,ser.class& id+2 F public void save,ser*,ser user+ D getHibernate!emplate*+.save'r,pdate*user+2 if *log.is-ebug1nabled*++ D log.debug*Huser$d set to: H O user.get$d*++2 F F public void remove,ser*4ong id+ D 'b#ect user B getHibernate!emplate*+.load*,ser.class& id+2 getHibernate!emplate*+.delete*user+2 F F ": Ho+ to prevent conc6rrent 6p0ate in Hi*ernate, A: version chec"ing used in hibernate when more then one thread trying to access same data. For e%ample : ,ser A edit the row of the !A.41 for update * $n the ,ser $nterface changing data - !his is user thin"ing time+ and in the same time ,ser . edit the same record for update and clic" the update. !hen ,ser A clic" the ,pdate and update done. Change made by user . is gone. $n hibernate you can

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

prevent slate ob#ect updatation using version chec"ing. Chec" the version of the row when you are updating the row. Pet the version of the row when you are fetching the row of the !A.41 for update. 'n the time of updation #ust fetch the version number and match with your version number * on the time of fetching+. !his way you can prevent slate ob#ect updatation. $teps 1: -eclare a variable Hversion$dH in your Class with setter and getter. public class Campign D private 4ong version$d2 private 4ong campign$d2 private String name2 public 4ong getMersion$d*+ D return version$d2 F public void setMersion$d*4ong version$d+ D this.version$d B version$d2 F public String get<ame*+ D return name2 F public void set<ame*String name+ D this.name B name2 F public 4ong getCampign$d*+ D return campign$d2 F private void setCampign$d*4ong campign$d+ D

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

this.campign$d B campign$d2 F F $tep ;. $n the .hbm.%ml file Gclass nameBHbeans.CampignH tableBHCAMC$P<H optimistic-loc"BHversionHI Gid nameBHcampign$dH typeBHlongH columnBHcidHI Ggenerator classBHse)uenceHI Gparam nameBHse)uenceHICAMC$P<J$-JS1 GEparamI GEgeneratorI GEidI Gversion nameBHversion$dH typeBHlongH columnBHversionH EI Gproperty nameBHnameH columnBHcJnameHEI GEclassI $tep 5. Create a column name HversionH in the CAMC$P< table. $tep <. $n the code EE foo is an instance loaded by a previous Session session B sf.openSession*+2 int oldMersion B foo.getMersion*+2 session.load* foo& foo.getQey*+ +2 if * oldMersionLBfoo.getMersion + throw new Stale'b#ectState1%ception*+2 foo.setCroperty*HbarH+2

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

session.flush*+2 session.connection*+.commit*+2 session.close*+2 8ou can handle Stale'b#ectState1%ception*+ and do what ever you want. 8ou can display error message. Hibernate autumatically createEupdate the version number when you updateEinsert any row in the table. ": !hat is version checking in Hi*ernate or Ho+ to han01e 6ser think time 6sing hi*ernate , A: version chec"ing used in hibernate when more then one thread trying to access same data. As we already have discussed in the previous e%ample. ,ser A edit the row of the !A.41 for update * $n the ,ser $nterface changing data - !his is user thin"ing time+ and in the same time ,ser . edit the same record for update and clic" the update. ": ransaction +ith p1ain 8-B7 in Hi*ernate , A: $f you don0t have 5!A and don0t want to deploy it along with your application& you will usually have to fall bac" to 5-.C transaction demarcation. $nstead of calling the 5-.C AC$ you better use Hibernate0s !ransaction and the built-in session-per-re)uest functionality: !o enable the thread-bound strategy in your Hibernate configuration: set hibernate.transaction.factoryJclass to org.hibernate.transaction.5-.C!ransactionFactory set hibernate.currentJsessionJconte%tJclass to thread Session session B factory.openSession*+2 !ransaction t% B null2 try D t% B session.begin!ransaction*+2 EE -o some wor" session.load*...+2 session.persist*...+2 t%.commit*+2 EE Flush happens automatically F

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

catch *(untime1%ception e+ D t%.rollbac"*+2 throw e2 EE or display error message F finally D session.close*+2 F ": !hat are the genera1 consi0erations or *est practices )or 0e)ining 3o6r Hi*ernate persistent c1asses, A: 3.8ou must have a default no-argument constructor for your persistent classes and there should be getRRR*+ *i.e accessorEgetter+ and setRRR* i.e. mutatorEsetter+ methods for all your persistable instance variables. 6.8ou should implement the e)uals*+ and hashCode*+ methods based on your business "ey and it is important not to use the id field in your e)uals*+ and hashCode*+ definition if the id field is a surrogate "ey *i.e. Hibernate managed identifier+. !his is because the Hibernate only generates and sets the field when saving the ob#ect. 9. $t is recommended to implement the Seriali/able interface. !his is potentially useful if you want to migrate around a multi-processor cluster. :.!he persistent class should not be final because if it is final then la/y loading cannot be used by creating pro%y ob#ects. ": -i))erence *et+een session.6p0ate./ an0 session.1ock./ in Hi*ernate , A: .oth of these methods and save'r,pdate*+ method are intended for reattaching a detached ob#ect. !he session.loc"*+ method simply reattaches the ob#ect to the session without chec"ing or updating the database on the assumption that the database in sync with the detached ob#ect. $t is the best practice to use either session.update*..+ or session.save'r,pdate*+.

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

,se session.loc"*+ only if you are absolutely sure that the detached ob#ect is in sync with your detached ob#ect or if it does not matter because you will be overwriting all the columns that would have changed later on within the same transaction. 1ach interaction with the persistent store occurs in a new Session. However& the same persistent instances are reused for each interaction with the database. !he application manipulates the state of detached instances originally loaded in another Session and then HreassociatesH them using Session.update*+ or Session.save'r,pdate*+. EE foo is an instance loaded by a previous Session foo.setCroperty*HbarH+2 session B factory.openSession*+2 session.save'r,pdate*foo+2 session.flush*+2 session.connection*+.commit*+2 session.close*+2 8ou may also call loc"*+ instead of update*+ and use 4oc"Mode.(1A- *performing a version chec"& bypassing all caches+ if you are sure that the ob#ect has not been modified. ": -i))erence *et+een get76rrent$ession./ an0 open$ession./ in Hi*ernate , A: getCurrentSession*+ : !he Hcurrent sessionH refers to a Hibernate Session bound by Hibernate behind the scenes& to the transaction scope. A Session is opened when getCurrentSession*+ is called for the first time and closed when the transaction ends. $t is also flushed automatically before the transaction commits. 8ou can call getCurrentSession*+ as often and anywhere you want as long as the transaction runs. !o enable this strategy in your Hibernate configuration: set hibernate.transaction.managerJloo"upJclass to a loo"up strategy for your 511 container set hibernate.transaction.factoryJclass to org.hibernate.transaction.5!A!ransactionFactory

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

'nly the Session that you obtained with sf.getCurrentSession*+ is flushed and closed automatically. 1%ample : try D ,ser!ransaction t% B *,ser!ransaction+new $nitialConte%t*+ .loo"up*H#ava:compE,ser!ransactionH+2 t%.begin*+2 EE -o some wor" sf.getCurrentSession*+.create uery*...+2 sf.getCurrentSession*+.persist*...+2 t%.commit*+2 F catch *(untime1%ception e+ D t%.rollbac"*+2 throw e2 EE or display error message F openSession*+ : $f you decide to use manage the Session yourself the go for sf.openSession*+ & you have to flush*+ and close*+ it. $t does not flush and close*+ automatically. 1%ample : ,ser!ransaction t% B *,ser!ransaction+new $nitialConte%t*+ .loo"up*H#ava:compE,ser!ransactionH+2 Session session B factory.openSession*+2 try D t%.begin*+2 EE -o some wor"

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

session.create uery*...+2 session.persist*...+2 session.flush*+2 EE 1%tra wor" you need to do t%.commit*+2 F catch *(untime1%ception e+ D t%.rollbac"*+2 throw e2 EE or display error message F finally D session.close*+2 EE 1%tra wor" you need to do F ": -i))erence *et+een session.save%r#p0ate./ an0 session.merge./, A: save%r#p0ate./ 0oes the )o11o+ing: if the ob#ect is already persistent in this session& do nothing if another ob#ect associated with the session has the same identifier& throw an e%ception if the ob#ect has no identifier property& save*+ it if the ob#ect0s identifier has the value assigned to a newly instantiated ob#ect& save*+ it if the ob#ect is versioned *by a GversionI or GtimestampI+& and the version property value is the same value assigned to a newly instantiated ob#ect& save*+ it otherwise update*+ the ob#ect merge./ is ver3 0i))erent: if there is a persistent instance with the same identifier currently associated with the session& copy the state of the given ob#ect onto the persistent instance. if there is no persistent instance currently associated with the session& try to load it from the database& or create a new persistent instance the persistent instance is returned. !he given instance does not become associated with the session& it remains detached

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

": ?i1ter in Hi*ernate +ith E4amp1e, A: ,S1( * $- $<!& ,S1(<AM1 MA(CHA(& AC!$MA!1- .''41A<+ - !A.41 public class ,ser D private int id2 private String username2 private boolean activated2 public boolean isActivated*+ D return activated2 F public void setActivated*boolean activated+ D this.activated B activated2 F public int get$d*+ D return id2 F public void set$d*int id+ D this.id B id2 F public String get,sername*+ D return username2 F public void set,sername*String username+

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

D this.username B username2 F F ----------------------------------------------------------------G7%ml versionB03.?0 encodingB0utf-@07I GL-'C!8C1 hibernate-mapping C,.4$C H-EEHibernateEHibernate Mapping -!-EE1<H Hhttp:EEhibernate.sourceforge.netEhibernate-mapping-9.?.dtdHI Ghibernate-mappingI Gclass nameBH,serHI Gid nameBHidH typeBHintHI Ggenerator classBHnativeHEI GEidI Gproperty nameBHusernameH typeBHstringH lengthBH96HEI Gproperty nameBHactivatedH typeBHbooleanHEI Gfilter nameBHactivatedFilterH conditionBH:activatedCaram B activatedHEI GEclassI Gfilter-def nameBHactivatedFilterHI Gfilter-param nameBHactivatedCaramH typeBHbooleanHEI GEfilter-defI GEhibernate-mappingI ----------------------------------------------------------------Save and Fetch using filter e%ample ,ser user3 B new ,ser*+2 user3.set,sername*Hname3H+2 user3.setActivated*false+2

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

session.save*user3+2 ,ser user6 B new ,ser*+2 user6.set,sername*Hname6H+2 user6.setActivated*true+2 session.save*user6+2 ,ser user9 B new ,ser*+2 user9.set,sername*Hname9H+2 user9.setActivated*true+2 session.save*user9+2 ,ser user: B new ,ser*+2 user:.set,sername*Hname:H+2 user:.setActivated*false+2 session.save*user:+2 All the four user saved to -ata .ase ,ser !able. <ow Fetch the ,ser using Filter.. Filter filter B session.enableFilter*HactivatedFilterH+2 filter.setCarameter*HactivatedCaramH&new .oolean*true++2 uery )uery B session.create uery*Hfrom ,serH+2 $terator results B )uery.iterate*+2 while *results.has<e%t*++ D ,ser user B *,ser+ results.ne%t*+2 System.out.print*user.get,sername*+ O H is H+2 F Puess the (esult : name6 name9

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

.ecause Filer is filtering * only true value+ data before )uery e%ecute. ": 7riteria "6er3 +o 7on0ition A: Criteria uery !wo Condition- 1%ample Gclass nameBHcom.bean.'rgani/ationH tableBH'(PA<$SA!$'<HI Gid nameBHorg$dH columnBH'(PJ$-H typeBHlongHI Ggenerator classBHnativeHEI GEidI Gproperty nameBHorgani/ation<ameH lengthBH;??HEI columnBH'(PA<$SA!$'<J<AM1H typeBHstringH

Gproperty nameBHtownH columnBH!'K<H typeBHstringH lengthBH6??HEI Gproperty nameBHstatusCodeH columnBHS!A!,SH typeBHstringH lengthBH3HEI GEclassI 4ist of organi/ation where town e)uals to pune and status B HAH. 4ist organi/ation4ist B session.createCriteria*'rgani/ation.class+ .add*(estrictions.e)*HtownH&HpuneH++ .add*(estrictions.e)*HstatusCodeH&HAH++ .list*+2 ": Ho+ can I avoi0 n@1 $"9 $E9E7 A6eries +hen r6nning a Hi*ernate A6er3, A: Follow the best practices guideL 1nsure that all GclassI and GcollectionI mappings specify la/yBHtrueH in Hibernate6 *this is the new default in Hibernate9+. ,se H 4 41F! 5'$< F1!CH to specify which associations you need to be retrieved in the initial S 4 S141C!. A second way to avoid the nO3 selects problem is to use fetchBHsubselectH in Hibernate9. $f you are still unsure& refer to the Hibernate documentation and Hibernate in Action.

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

": E4p1ain the hi*ernate N@1 pro*1em an0 its so16tion, A: 'ro*1em $n a previous pitfall *Avoiding !he <O3 Selects Croblem+ we showed how the <O3 selects problem could inadvertently arise when not using la/y initiali/ation. A more subtle cause for the <O3 selects problem is from not using database #oins correctly to return the data our application uses. $f an application does use the correct fetching strategy to load the data it needs& it may end up ma"ing more round trips to the database than necessary. Ke illustrate by returning to the e%ample of the class Contact& which has a one-to-many relationship with Manufacturer *that is& there is one Contact for many Manufacturers+ . Since the Contract is uses la/y initiali/ation in its hbm.xml file
<class name="example.domain.Contact" table="CONTACT" lazy = "true"> ... < class>

it will not automatically be la/ily initiali/ed as part of the e%ecution of the H 4 "from Manufacturer manufacturer". !his )uery will not load the data for Contact& but will instead load a pro%y to the real data. !he problem is when you run this )uery but decide in writing your application that you do want to retrieve all the contacts for the returned set of manufacturers
!uery "uery = #et$upport%&.#et$ession%&.create!uery%"from Manufacturer manufacturer"&' (ist list = "uery.list%&' for %)terator iter = list.iterator%&' iter.*asNext%&'& + Manufacturer manufacturer = %Manufacturer& iter.next%&' $ystem.out.println%manufacturer.#etContact%&.#etName%&&' ,

Since the initial )uery "from Manufacturer manufacturer" does not initiali/e the Contact instances& an additional separate )uery is needed to do so for each Contact loaded. Again& you get the <O3 selects problem. $o16tion Ke solve this problem by ma"ing sure that the initial )uery fetches all the data needed to load the ob#ects we need in their appropriately initiali/ed state. 'ne way of doing this is using an H 4 fetch #oin.

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

Ke use the H 4 "from Manufacturer manufacturer -oin fetc* manufacturer.contact contact" with the fetch statement. !his results in an inner #oin:
select MAN./ACT.010.id from manufacturer and contact ... from MAN./ACT.010 inner -oin CONTACT on MAN./ACT.010.CONTACT2)3=CONTACT.id

,sing a Criteria )uery we can get the same result from


Criteria criteria = session.createCriteria%Manufacturer.class&' criteria.set/etc*Mode%"contact"4 /etc*Mode.1A510&'

which creates the S 4


select MAN./ACT.010.id from MAN./ACT.010 left outer -oin CONTACT on MAN./ACT.010.CONTACT2)3=CONTACT.id 6*ere 7=7

$n both cases& our )uery returns a list of Manufacturer ob#ects with the contact initiali/ed. 'nly one )uery needs to be run to return all the contact and manufacturer information re)uired for the e%ample. ": Ho+ 0oes Va16e rep1acement in Bessage Reso6rce B6n01e +ork, A: $n the resource bundle file& you can define a template li"e: errors.re)uiredBD?F is re)uired. Action1rrors errors B new Action1rrors*+2 errors.add*Action1rrors.P4'.A4J1(('(& new Action1rror*Herror.custformH&HFirst <ameH++2 !hen the 1rror message is : First <ame is re)uired. 'ther constructors are public Action1rror*String "ey& 'b#ect value?& 'b#ect value3+ ... public Action1rror*String "ey& 'b#ectTU values+2 ": -i))erence *et+een 1ist./ an0 iterate./ iCn Hi*ernate,

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

A: $f instances are already be in the session or second-level cache iterate*+ will give better performance. $f they are not already cached& iterate*+ will be slower than list*+ and might re)uire many database hits for a simple )uery. ": -e1eting persistent o*jects A: Session.delete*+ will remove an ob#ect0s state from the database. 'f course& your application might still hold a reference to a deleted ob#ect. $t0s best to thin" of delete*+ as ma"ing a persistent instance transient. sess.delete*cat+2 ": $"9 statements e4ec6tion or0er. A: 3. all entity insertions& in the same order the corresponding ob#ects were saved using Session.save*+ 6. all entity updates 9. all collection deletions :. all collection element deletions& updates and insertions ;. all collection insertions =. all entity deletions& in the same order the corresponding ": Bo0i)3ing persistent o*jects, A: -omesticCat cat B *-omesticCat+ sess.load* Cat.class& new 4ong*=A+ +2 cat.set<ame*HCQH+2 sess.flush*+2 EE changes to cat are automatically detected and persisted !o -ata .ase. <o need any session.update*+ call. ": $"9 "6eries In Hi*ernate.. A: 8ou may e%press a )uery in S 4& using createS 4 uery*+ and let Hibernate ta"e care of the mapping from result sets to ob#ects. <ote that you may at any time call session.connection*+ and use the 5-.C Connection directly. $f you chose to use the Hibernate AC$& you must enclose S 4 aliases in braces:

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

4ist cats B session.createS 4 uery* HS141C! Dcat.VF F('M CA! DcatF KH1(1 ('K<,MG3?H& HcatH& Cat.class +.list*+2 4ist cats B session.createS 4 uery* HS141C! DcatF.$- AS Dcat.idF& DcatF.S1R AS Dcat.se%F& H O HDcatF.MA!1 AS Dcat.mateF& DcatF.S,.C4ASS AS Dcat.classF& ... H O HF('M CA! DcatF KH1(1 ('K<,MG3?H& HcatH& Cat.class +.list*+ S 4 )ueries may contain named and positional parameters& #ust li"e Hibernate )ueries. ": EA6a1 an0 Not EA6a1 criteria A6er3. A: 1)ual and <ot 1)ual criteria )uery- 1%ample Gclass nameBHcom.bean.'rgani/ationH tableBH'(PA<$SA!$'<HI Gid nameBHorg$dH columnBH'(PJ$-H typeBHlongHI Ggenerator classBHnativeHEI GEidI Gproperty nameBHorgani/ation<ameH lengthBH;??HEI GEclassI 4ist of organisation where town e)uals to pune. 4ist organi/ation4ist B session.createCriteria*'rgani/ation.class+.add*(estrictions.e) *HtownH&HpuneH+ +.list*+2 4ist of organisation where town not e)uals pune. 4ist organi/ation4ist B session.createCriteria *'rgani/ation.class +. add*(estrictions.ne *HtownH&HpuneH++. list*+2 ": !hat is *i( 0irectiona1 mapping& Dive e4amp1e o) Bi0irectiona1 one(to(man3 +ith an in0e4e0 co11ection, A: Hibernate 6 does not support bidirectional *inverseBHtrueH+ one-to-many associations with an inde%ed collection *list& map or array+ as the HmanyH end. $f you want to "eep the inverseBHtrueH attribute and want to use an inde%ed collection& you have to handle the inde% of the collection manually.!he following solution wor"s with a list. columnBH'(PA<$SA!$'<J<AM1H typeBHstringH

Gproperty nameBHtownH columnBH!'K<H typeBHstringH lengthBH6??HEI

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

!he same method can be used when using an array or a map. *See below+ Mapping Gclass nameBHnet.sf.test.CarentH tableBHparentHI Gid nameBHidH columnBHidH typeBHlongH unsaved-valueBHnullHI Ggenerator classBHse)uenceHI Gparam nameBHse)uenceHIS1 J-1FA,4!GEparamI GEgeneratorI GEidI Glist nameBHchildrenH la/yBHtrueH inverseBHtrueHI G"ey columnBHparentJidHEI Ginde% columnBHinde%JcolHEI Gone-to-many classBHnet.sf.test.ChildHEI GElistI GEclassI Gclass nameBHnet.sf.test.ChildH tableBHchildHI Gid nameBHidH columnBHidH typeBHlongH unsaved-valueBHnullHI Ggenerator classBHse)uenceHI Gparam nameBHse)uenceHIS1 J-1FA,4!GEparamI GEgeneratorI GEidI Gmany-to-one nameBHparentH columnBHparentJidH not-nullBHtrueHEI Gproperty nameBHinde%H columnBHinde%JcolH typeBHintH updateBHtrueH insertBHtrueHEI GEclassI !he inverseBHtrueH is set to the one side. !he column name for the inde% property on the child is the same as the inde% column of the one-tomany mapping on the parent.

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

": !hat is hi*ernate entit3 manager, A: Hibernate 1ntityManager implements: V !he standard 5ava Cersistence management AC$ V !he standard 5ava Cersistence uery 4anguage V !he standard 5ava Cersistence ob#ect lifecycle rules V !he standard 5ava Cersistence configuration and pac"aging Hibernate 1ntityManager wraps the powerful and mature Hibernate Core. 8ou can fall bac" to Hibernate native AC$s& native S 4& and native 5-.C whenever necessary. !he Hibernate 5ava Cersistence provider is the default persistence provider of the 5.oss 15. 9.? implementation and bundled with the 5.oss Application Server. ": !hat is Hi*ernate Annotations, A: Hibernate& li"e all other ob#ectErelational mapping tools& re)uires meta data that governs the transformation of data from one representation to the other *and vice versa+. As an option& you can now use 5-Q ;.? annotations for ob#ectErelational mapping with Hibernate 9.6. 8ou can use annotations in addition to or as a replacement of RM4 mapping metadata. !he Hibernate Annotations pac"age includes: Standardi/ed 5ava Cersistence and 15. 9.? *5S( 66?+ ob#ectErelational mapping annotations Hibernate-specific e%tension annotations for performance optimi/ation and special mappings 8ou can use Hibernate e%tension annotations on top of standardi/ed 5ava Cersistence annotations to utili/e all native Hibernate features. (e)uirements: At a minimum& you need 5-Q ;.? and Hibernate Core& but no application server or 15. 9.? container. 8ou can use Hibernate Core and Hibernate Annotations in any 5ava 11 ;.? or 5ava S1 ;.? environment. ": 7asca0e $ave or #p0ate in Hi*ernate ,

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

A: Cascade Save or ,pdate - $n one to Many- 1RAMC41 C('C1SSJ!8C1J4'M *C('C1SSJ!8C1J$- number& C('C1SSJ!8C1J<AM1 varchar+ - !A.41 C('C1SS *C('C1SSJ$- number&C('C1SSJ<AM1 varchar&C('C1SSJ!8C1J$- number+- !A.41 public class Crocess!ype.ean D private 4ong process!ype$d2 private String process!ype<ame2 EVV V Nreturn (eturns the process!ype$d. VE public 4ong getCrocess!ype$d*+ D return process!ype$d2 F EVV V Nparam process!ype$d !he process!ype$d to set. VE public void setCrocess!ype$d*4ong process!ype$d+ D this.process!ype$d B process!ype$d2 F EVV V Nreturn (eturns the process!ype<ame. VE public String getCrocess!ype<ame*+ D return process!ype<ame2 F EVV V Nparam process!ype<ame !he process!ype<ame to set. VE public void setCrocess!ype<ame*String process!ype<ame+ D

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

this.process!ype<ame B process!ype<ame2 F F public class Crocess.ean D private 4ong process$d2 private String process<ame B HH2 private Crocess!ype.ean process!ype2 public 4ong getCrocess$d*+ D return process$d2 F EVV V Nparam process$d !he process$d to set. VE public void setCrocess$d*4ong process$d+ D this.process$d B process$d2 F EVV V Nreturn (eturns the process<ame. VE public String getCrocess<ame*+ D return process<ame2 F EVV V Nparam process<ame !he process<ame to set. VE public void setCrocess<ame*String process<ame+ D

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

this.process<ame B process<ame2 F EVV V Nreturn (eturns the process!ype. VE public Crocess!ype.ean getCrocess!ype*+ D return process!ype2 F EVV V Nparam process!ype !he process!ype to set. VE public void setCrocess!ype*Crocess!ype.ean process!ype+ D this.process!ype B process!ype2 F F Gclass nameBHcom.bean.Crocess.eanH tableBHC('C1SSHI Gid nameBHprocess$dH typeBHlongH columnBHC('C1SSJ$-H EI Gproperty nameBHprocess<ameH columnBHC('C1SSJ<AM1H typeBHstringH lengthBH;?H EI Gmany-to-one nameBHprocess!ypeH columnBHC('C1SSJ!8C1J$-H classBHCrocess!ype.eanH cascadeBHsave-updateH EI GEclassI Gclass nameBHcom.bean.Crocess!ype.eanH tableBHC('C1SSJ!8C1J4'MHI Gid nameBHprocess!ype$dH typeBHlongH columnBHC('C1SSJ!8C1J$-H EI Gproperty nameBHprocess!ype<ameH columnBHC('C1SSJ!8C1J<AM1H

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

typeBHstringH lengthBH;?H EI GEclassI --------------------------------------------------------------------------------Save 1%ample Code Crocess!ype.ean pstype B new Crocess!ype.ean*+2 pstype.setCrocess!ype<ame*H5ava CrocessH+2 Crocess.ean process B new Crocess.ean*+2 process.setCrocess<ame*HCroductionH+ Crocess.ean.setCrocess!ype*pstype+2 EE session.save*pstype+2 -- !his save not re)uired because of in the mapping file cascadeBHsave-updateH session.save*process+2 - !his will insert both Crocess.ean and Crocess!ype.ean2

": %ne o Ban3 Bi(0irectiona1 Re1ation in Hi*ernate, A: .i--ireCtional 'ne to Many (elation- 1RAMC41 C('C1SSJ!8C1J4'M *C('C1SSJ!8C1J$- number& C('C1SSJ!8C1J<AM1 varchar+ - !A.41 C('C1SS *C('C1SSJ$- number&C('C1SSJ<AM1 varchar&C('C1SSJ!8C1J$- number+- !A.41 public class Crocess!ype.ean D private 4ong process!ype$d2 private String process!ype<ame2 private 4ist processes B null2 EVV V Nreturn (eturns the processes. VE public 4ist getCrocesses*+ D return processes2

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

F EVV V Nparam processes !he processes to set. VE public void setCrocesses*4ist processes+ D this.processes B processes2 F EVV V Nreturn (eturns the process!ype$d. VE public 4ong getCrocess!ype$d*+ D return process!ype$d2 F EVV V Nparam process!ype$d !he process!ype$d to set. VE public void setCrocess!ype$d*4ong process!ype$d+ D this.process!ype$d B process!ype$d2 F EVV V Nreturn (eturns the process!ype<ame. VE public String getCrocess!ype<ame*+ D return process!ype<ame2 F EVV V Nparam process!ype<ame !he process!ype<ame to set. VE

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

public void setCrocess!ype<ame*String process!ype<ame+ D this.process!ype<ame B process!ype<ame2 F F public class Crocess.ean D private 4ong process$d2 private String process<ame B HH2 private Crocess!ype.ean process!ype2 public 4ong getCrocess$d*+ D return process$d2 F EVV V Nparam process$d !he process$d to set. VE public void setCrocess$d*4ong process$d+ D this.process$d B process$d2 F EVV V Nreturn (eturns the process<ame. VE public String getCrocess<ame*+ D return process<ame2 F EVV V Nparam process<ame !he process<ame to set. VE public void setCrocess<ame*String process<ame+ D this.process<ame B process<ame2

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

F EVV V Nreturn (eturns the process!ype. VE public Crocess!ype.ean getCrocess!ype*+ D return process!ype2 F EVV V Nparam process!ype !he process!ype to set. VE public void setCrocess!ype*Crocess!ype.ean process!ype+ D this.process!ype B process!ype2 F F Gclass nameBHcom.bean.Crocess.eanH tableBHC('C1SSHI Gid nameBHprocess$dH typeBHlongH columnBHC('C1SSJ$-H EI Gproperty nameBHprocess<ameH columnBHC('C1SSJ<AM1H typeBHstringH lengthBH;?H EI Gmany-to-one nameBHprocess!ypeH columnBHC('C1SSJ!8C1J$-H la/yBHfalseH EI GEclassI Gclass nameBHcom.bean.Crocess!ype.eanH tableBHC('C1SSJ!8C1J4'MHI Gid nameBHprocess!ype$dH typeBHlongH columnBHC('C1SSJ!8C1J$-H EI Gproperty nameBHprocess!ype<ameH columnBHC('C1SSJ!8C1J<AM1H typeBHstringH lengthBH;?H EI Gbag nameBHprocessesH inverseBHtrueH cascadeBHdeleteH la/yBHfalseHI G"ey columnBHC('C1SSJ!8C1J$-H EI

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

Gone-to-many classBHcom.bean.Crocess.eanH EI GEbagI GEclassI ": %ne o Ban3 Bapping #sing 9ist , A: K($!1( *$- $<!&<AM1 MA(CHA(+ - !A.41 S!'(8 *$- $<!&$<F' MA(CHA(&CA(1<!J$- $<!+ - !A.41 'ne writer can have multiple stories.. ------------------------------------------------------------Mapping File... G7%ml versionBH3.?H encodingBH,!F-@H7I GL-'C!8C1 hibernate-mapping C,.4$C H-EEHibernateEHibernate Mapping -!-EE1<H Hhttp:EEhibernate.sourceforge.netEhibernate-mapping-6.?.dtdHI Ghibernate-mappingI Gclass nameBHKriterH tableBHK($!1(HI Gid nameBHidH unsaved-valueBH?HI Ggenerator classBHincrementHEI GEidI Glist nameBHstoriesH cascadeBHallHI G"ey columnBHparentJidHEI Gone-to-many classBHStoryHEI GElistI Gproperty nameBHnameH typeBHstringHEI GEclassI Gclass nameBHStoryH tableBHstoryHI

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

Gid nameBHidH unsaved-valueBH?HI Ggenerator classBHincrementHEI GEidI Gproperty nameBHinfoHEI GEclassI GEhibernate-mappingI ------------------------------------------------------public class Kriter D private int id2 private String name2 private 4ist stories2 public void set$d*int i+ D id B i2 F public int get$d*+ D return id2 F public void set<ame*String n+ D name B n2 F public String get<ame*+ D return name2 F public void setStories*4ist l+ D stories B l2 F public 4ist getStories*+ D

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

return stories2 F F -------------------------------------------------public class Story D private int id2 private String info2 public Story*+D F public Story*String info+ D this.info B info2 F public void set$d*int i+ D id B i2 F public int get$d*+ D return id2 F public void set$nfo*String n+ D info B n2 F public String get$nfo*+ D return info2 F F ---------------------------------------------------Save 1%ample ..

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

Kriter wr B new Kriter*+2 wr.set<ame*H-asH+2 Array4ist list B new Array4ist*+2 list.add*new Story*HStory <ame 3H++2 list.add*new Story*HStory <ame 6H++2 wr.setStories*list+2 !ransaction transaction B null2 try D transaction B session.begin!ransaction*+2 session.save*sp+2 transaction.commit*+2 F catch *1%ception e+ D if *transaction LB null+ D transaction.rollbac"*+2 throw e2 F F finally D session.close*+2 F ": Ban3 o Ban3 Re1ation In Hi*ernate , A: .est 1%ample..for Many to Many in Hibernate .. 1M1<!S * uid int& name MA(CHA(+ !able SC1AQ1(S * uid int& first<ame MA(CHA(+ !able 1M1<!JSC1AQ1(S *elt int& eventJid int& spea"erJid int+ !able ----------------------------------------------------------import #ava.util.Set2 import #ava.util.HashSet2

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

public class Spea"erD private 4ong id2 private String first<ame2 private Set events2 public 4ong get$d*+ D return id2 F public void set$d*4ong id+ D this.id B id2 F public String getFirst<ame*+ D return first<ame2 F public void setFirst<ame*String first<ame+ D this.first<ame B first<ame2 F public Set get1vents*+ D return this.events2 F public void set1vents*Set events+ D this.events B events2 F private void add1vent*1vent event+ D if *events BB null+ D events B new HashSet*+2 F events.add*event+2 F

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

F -------------------------------------------------------import #ava.util.-ate2 import #ava.util.Set2 public class 1ventD private 4ong id2 private String name2 private Set spea"ers2 public void set$d*4ong id+ D this.id B id2 F public 4ong get$d*+ D return id2 F public String get<ame*+ D return name2 F public void set<ame*String name+ D this.name B name2 F public void setSpea"ers*Set spea"ers+ D this.spea"ers B spea"ers2 F public Set getSpea"ers*+ D return spea"ers2 F F

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

-------------------------------------------------------------1vent.hbm.%ml G7%ml versionBH3.?H7I GL-'C!8C1 hibernate-mapping C,.4$C H-EEHibernateEHibernate Mapping -!- 6.?EE1<H Hhttp:EEhibernate.sourceforge.netEhibernate-mapping-6.?.dtdHI Ghibernate-mappingI Gclass nameBH1ventH tableBHeventsHI Gid nameBHidH columnBHuidH typeBHlongH unsaved-valueBHnullHI Ggenerator classBHincrementHEI GEidI Gproperty nameBHnameH typeBHstringH lengthBH3??HEI Gset nameBHspea"ersH tableBHeventJspea"ersH cascadeBHallHI G"ey columnBHeventJidHEI Gmany-to-many classBHSpea"erHEI GEsetI GEclassI GEhibernate-mappingI -----------------------------------------------------------------Spea"er.hbm.%ml G7%ml versionBH3.?H7I GL-'C!8C1 hibernate-mapping C,.4$C H-EEHibernateEHibernate Mapping -!- 6.?EE1<H Hhttp:EEhibernate.sourceforge.netEhibernate-mapping-6.?.dtdHI Ghibernate-mappingI Gclass nameBHSpea"erH tableBHspea"ersHI Gid nameBHidH columnBHuidH typeBHlongHI

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

Ggenerator classBHincrementHEI GEidI Gproperty nameBHfirst<ameH typeBHstringH lengthBH6?HEI Gset nameBHeventsH tableBHeventJspea"ersH cascadeBHallHI G"ey columnBHspea"erJidHEI Gmany-to-many classBH1ventHEI GEsetI GEclassI GEhibernate-mappingI ---------------------------------------------------------------------Save and Fetch 1%ample 1vent event B new 1vent*+2 event.set<ame*H$nverse testH+2 event.setSpea"ers*new HashSet*++2 event.getSpea"ers*+.add*new Spea"er*H(amH& event++2 event.getSpea"ers*+.add*new Spea"erMany!oMany*HSyamH& event++2 event.getSpea"ers*+.add*new Spea"erMany!oMany*H5aduH& event++2 session.save*event+2 EEE Save All the -ata event B *1vent+ session.load*1vent.class& event.get$d*++2 Set spea"ers B event.getSpea"ers*+2 for *$terator i B spea"ers.iterator*+2 i.has<e%t*+2+ D Spea"er spea"er B *Spea"er+ i.ne%t*+2 System.out.println*spea"er.getFirst<ame*++2 System.out.println*spea"er.get$d*++2 F ": !hat 0oes session.re)resh./ 0o , A: $t is possible to re-load an ob#ect and all its collections at any time& using the refresh*+ method. !his

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

is useful when database triggers are used to initiali/e some of the properties of the ob#ect. For 1%ample - !riger on catJname coulmn. !rigger is updating hitJcount coulmn in the same Cat !able. Khen $nsert data into Cat !A.41 trigger update hitJcount coulmn to 3. sess.refresh*+ reload all the data. <o need again to select call. sess.save*cat+2 sess.flush*+2 EEforce the S 4 $<S1(! sess.refresh*cat+2 EEre-read the state *after the trigger e%ecutes+ ": Hi*ernate set6p 6sing .c)g.4m1 )i1e , A: !he RM4 configuration file is by default e%pected to be in the root o your C4ASSCA!H. Here is an e%ample: G7%ml versionB03.?0 encodingB0utf-@07I GL-'C!8C1 hibernate-configuration C,.4$C H-EEHibernateEHibernate Configuration -!-EE1<H Hhttp:EEhibernate.sourceforge.netEhibernate-configuration-9.?.dtdHI Ghibernate-configurationI GL-- a SessionFactory instance listed as E#ndiEname --I Gsession-factory nameBH#ava:hibernateESessionFactoryHI GL-- properties --I Gproperty nameBHconnection.datasourceHI#ava:EcompEenvE#dbcEMy-.GEpropertyI Gproperty nameBHdialectHIorg.hibernate.dialect.MyS 4-ialectGEpropertyI Gproperty nameBHshowJs)lHIfalseGEpropertyI Gproperty nameBHtransaction.factoryJclassHI org.hibernate.transaction.5!A!ransactionFactory GEpropertyI Gproperty nameBH#ta.,ser!ransactionHI#ava:compE,ser!ransactionGEpropertyI GL-- mapping files --I Gmapping resourceBHorgEhibernateEauctionECost.hbm.%mlHEI

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

GEsession-factoryI GEhibernate-configurationI As you can see& the advantage of this approach is the e%ternali/ation of the mapping file names to configuration. !he hibernate.cfg.%ml is also more convenient once you have to tune the Hibernate cache. <ote that is your choice to use either hibernate.properties or hibernate.cfg.%ml& both are e)uivalent& e%cept for the above mentioned benefits of using the RM4 synta%. Kith the RM4 configuration& starting Hibernate is then as simple as SessionFactory sf B new Configuration*+.configure*+.buildSessionFactory*+2 8ou can pic" a different RM4 configuration file using SessionFactory sf B new Configuration*+.configure*Hcatdb.cfg.%mlH+.buildSessionFactory*+2 Cost.hbm.%ml -----I loo"s li"e G7%ml versionBH3.?H7I GL-'C!8C1 hibernate-mapping C,.4$C H-EEHibernateEHibernate Mapping -!- 9.?EE1<H Hhttp:EEhibernate.sourceforge.netEhibernate-mapping-9.?.dtdHI Ghibernate-mappingI Gclass nameBHcom.bean.CostH tableBHC'S!HI Gid nameBHidH columnBH$-HI GEidI Gproperty nameBHis ueuedH typeBHintH columnBH$SJ ,1,1-HEI Gproperty nameBH)ueue-ateH typeBHtimestampH columnBH ,1,1J-A!1HEI Gproperty nameBHlastModified-ateH typeBHtimestampH columnBH4AS!JM'-$F$1-J-A!1HEI Gproperty nameBHlastModified.yH columnBH4AS!JM'-$F$1-J.8HEI Gproperty nameBHamountH columnBHAM',<!H typeBHdoubleHEI Gproperty nameBHcurrencyCodeH columnBHC,((1<C8JC'-1H EI Gproperty nameBHyearH columnBH81A(HEI Gproperty nameBH)uarterH columnBH ,A(!1(HEI

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

Gproperty nameBHcostModFlagH typeBHintH columnBHC'S!JM'-JF4APHEI Gproperty nameBHparent$dH columnBHCA(1<!J$-HEI Gproperty nameBHoldCarent$dH columnBH'4-JCA(1<!J$-HEI Gproperty nameBHparent$dModFlagH typeBHintH columnBHCA(1<!J$-JM'-JF4APHEI Gproperty nameBHdate$ncurredH typeBHtimestampH columnBH-A!1J$<C,((1-HEI Gproperty nameBH,S-AmountH columnBH,S-JAM',<!H typeBHdoubleHEI Gproperty nameBHis-eletedH typeBHintH columnBH$SJ-141!1-HE2 n will be avilable in 6nd level cache ": Ho+ to get 8-B7 connections in hi*ernate, A: ,ser Session.connection*+ method to get 5-.C Connection. ": Ho+ +i11 3o6 con)ig6re Hi*ernate, A: Step 3I Cut Hibernate properties in the classpath. Step 6I Cut .hbm.%ml in class path 7 Code is Here to create session ...

pac"age com.dao2 import #ava.io.File2 import #ava.io.File$nputStream2 import #ava.util.Croperties2 import org.apache.log:#.4ogger2 import org.hibernate.Hibernate1%ception2 import org.hibernate.Session2 import org.hibernate.SessionFactory2 import org.hibernate.!ransaction2 import org.hibernate.cfg.Configuration2

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

public class Hibernate,til D protected static final 4ogger loggerB4ogger.get4ogger*Hibernate,til.class+2 public static String appHome B H<oH2 private static SessionFactory sessionFactory2 private static final !hread4ocal threadSession B new !hread4ocal*+2 private static final !hread4ocal thread!ransaction B new !hread4ocal*+2 EVV V $nitiali/e Hibernate Configuration VE public static void initMonitor*+D logger.info*HHibernate configureH+2 try D logger.info*HappHomeHOappHome+2 String pathJproperties B appHomeOFile.separatorCharOHhibernate.propertiesH2 String pathJmapping B appHomeOFile.separatorCharOHmappingJclasses.mys)l.hbm.%mlH2 EEString ecache B appHomeOFile.separatorCharOHehcache.%mlH2 Croperties propHibernate B new Croperties*+2 propHibernate.load*new File$nputStream*pathJproperties++2 Configuration configuration B new Configuration*+2 configuration.addFile*pathJmapping+2 configuration.setCroperties*propHibernate+2 EV try D CacheManager.create*ecache+2 F catch *Cache1%ception e+ D EE logger.log1rror*e+2 FVE sessionFactory B configuration.buildSessionFactory*+2

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

F catch *!hrowable e%+ D logger.error*H1%ception in initMonitorH&e%+2 throw new 1%ception$n$nitiali/er1rror*e%+2 F F EVV V Nreturn a Session Factory 'b#ect VE public static SessionFactory getSessionFactory*+ D logger.info*H$nside getSessionFactory methodH+2 try D if *sessionFactory BB null+ D initMonitor*+2 Felse D EEsessionFactory.getStatistics*+.logSummary*+2 F F catch *1%ception e+ D logger.error*H1%ception in getSessionFactoryH&e+2 F return sessionFactory2 F EVV V Nreturn Session . Start a Session VE public static Session getSession*+ D Session s B *Session+ threadSession.get*+2 logger.debug*HsessionHOs+2

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

if *s BB null+ D s B getSessionFactory*+.openSession*+2 threadSession.set*s+2 logger.debug*Hsession 3 WHOs+2 F return s2 F EVV V Close Session VE public static void closeSession*+D Session s B *Session+ threadSession.get*+2 threadSession.set*null+2 if *s LB null XX s.is'pen*++ D s.flush*+2 s.close*+2 F F EVV V Start a new database transaction. VE public static void begin!ransaction*+D !ransaction t% B null2 if *t% BB null+ D t% B getSession*+.begin!ransaction*+2 thread!ransaction.set*t%+2 F F

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

EVV V Commit the database transaction. VE public static void commit!ransaction*+D !ransaction t% B *!ransaction+ thread!ransaction.get*+2 try D if * t% LB null + D t%.commit*+2 F thread!ransaction.set*null+2 F catch *Hibernate1%ception e%+ D rollbac"!ransaction*+2 throw e%2 F F EVV V (ollbac" the database transaction. VE public static void rollbac"!ransaction*+D !ransaction t% B *!ransaction+ thread!ransaction.get*+2 try D thread!ransaction.set*null+2 if * t% LB null XX Lt%.wasCommitted*+ XX Lt%.was(olled.ac"*+ + D t%.rollbac"*+2 F F finally D closeSession*+2

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

F F F ": !hat are the Instance states in Hi*ernate, A: !he instance states in hibernate are: transient !he instance is not& and has never been associated with any persistence conte%t. $t has no persistent identity *primary "ey value+. persistent !he instance is currently associated with a persistence conte%t. $t has a persistent identity *primary "ey value+ and& perhaps& a corresponding row in the database. For a particular persistence conte%t& Hibernate guarantees that persistent identity is e)uivalent to 5ava identity *in-memory location of the ob#ect+. 0etache0 !he instance was once associated with a persistence conte%t& but that conte%t was closed& or the instance was seriali/ed to another process. $t has a persistent identity and& perhaps& a corresponding row in the database. For detached instances& Hibernate ma"es no guarantees about the relationship between persistent identity and 5ava identity. ": !hat are the core components in Hi*ernate , A: $ession?actor3 *org.hibernate.SessionFactory+ A threadsafe *immutable+ cache of compiled mappings for a single database. A factory for Session and a client of ConnectionCrovider. Might hold an optional *second-level+ cache of data that is reusable between transactions& at a process- or cluster-level. $ession *org.hibernate.Session+ A single-threaded& short-lived ob#ect representing a conversation between the application and the persistent store. Kraps a 5-.C connection. Factory for !ransaction. Holds a mandatory *first-level+ cache of persistent ob#ects& used when navigating the ob#ect graph or loo"ing up ob#ects by identifier.

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

Cersistent ob#ects and collections Short-lived& single threaded ob#ects containing persistent state and business function. !hese might be ordinary 5ava.eansEC'5's& the only special thing about them is that they are currently associated with *e%actly one+ Session. As soon as the Session is closed& they will be detached and free to use in any application layer *e.g. directly as data transfer ob#ects to and from presentation+. !ransient and detached ob#ects and collections $nstances of persistent classes that are not currently associated with a Session. !hey may have been instantiated by the application and not *yet+ persisted or they may have been instantiated by a closed Session. ransaction *org.hibernate.!ransaction+ *'ptional+ A single-threaded& short-lived ob#ect used by the application to specify atomic units of wor". Abstracts application from underlying 5-.C& 5!A or C'(.A transaction. A Session might span several !ransactions in some cases. However& transaction demarcation& either using the underlying AC$ or !ransaction& is never optional Architecture Hibernate 9.?.6 A 7onnection'rovi0er *org.hibernate.connection.ConnectionCrovider+ *'ptional+ A factory for *and pool of+ 5-.C connections. Abstracts application from underlying -atasource or -riverManager. <ot e%posed to application& but can be e%tendedEimplemented by the developer. ransaction?actor3 *org.hibernate.!ransactionFactory+ *'ptional+ A factory for !ransaction instances. <ot e%posed to the application& but can be e%tendedE implemented by the developer. E4tension Inter)aces Hibernate offers many optional e%tension interfaces you can implement to customi/e the behavior of your persistence layer. See the AC$ documentation for details. ": !hat is a Hi*ernate $ession, 7an 3o6 share a session o*ject *et+een 0i))erent thea0s, A: Session is a light weight and a non-threadsafe ob#ect *<o& you cannot share it between threads+ that represents a single unit-of-wor" with the database. Sessions are opened by a SessionFactory and then are closed when all wor" is complete. Session is the primary interface for the persistence service. A session obtains a database connection la/ily *i.e. only when re)uired+. !o avoid creating too many sessions !hread4ocal class can be used as shown below to get the current session no matter how many times you ma"e call to the currentSession*+ method.

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

public class Hibernate,til D public static final !hread4ocal local B new !hread4ocal*+2 public static Session currentSession*+ throws Hibernate1%ception D Session session B *Session+ local.get*+2 EEopen a new session if this thread has no session if*session BB null+ D session B sessionFactory.openSession*+2 local.set*session+2 F return session2 F F ": a00$ca1ar./ metho0 in hi*ernate... A: -ouble ma% B *-ouble+ sess.createS 4 uery*Hselect ma%*cat.weight+ as ma%Keight from cats catH+ .addScalar*Hma%KeightH& Hibernate.-',.41+2 .uni)ue(esult*+2 addScalar*+ method confim that ma%Keight is always double type. !his way you don0t need to chec" for it is double or not. ": Hi*ernate session.c1ose 0oes EnotE ca11 session.)16sh , A: session.close*+ don0t call session.flush*+ before closing the session. !his is the session.close*+ code in hibernate.#ar public Connection close*+ throws Hibernate1%ception D

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

log.trace* Hclosing sessionH +2 if * isClosed*+ + D throw new Session1%ception* HSession was already closedH +2 F

if * factory.getStatistics*+.isStatistics1nabled*+ + D factory.getStatistics$mplementor*+.closeSession*+2 F try D try D if * childSessions.y1ntityMode LB null + D $terator childSessions B childSessions.y1ntityMode.values*+.iterator*+2 while * childSessions.has<e%t*+ + D final Session$mpl child B * Session$mpl + childSessions.ne%t*+2 child.close*+2 F F F catch* !hrowable t + D EE #ust ignore F if * rootSession BB null + D return #dbcConte%t.getConnectionManager*+.close*+2 F else D

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

return null2 F F finally D setClosed*+2 cleanup*+2 F F ": !hat is the main 0i))erence *et+een Entit3 Beans an0 Hi*ernate , A: 3+$n 1ntity .ean at a time we can interact with only one data .ase. Khere as in Hibernate we can able to establishes the connections to more than 'ne -ata .ase. 'nly thing we need to write one more configuration file. 6+ 15. need container li"e Keblogic& KebSphare but hibernate don0t need. $t can be run on tomcat. 9+ 1ntity .eans does not support ''CS concepts where as Hibernate does. :+ Hibernate supports multi level cacheing& where as 1ntity .eans doesn0t. ;+ $n Hibernate C9C? can be used as a connection pool. =+ Hibernate is container independent. 15. not. ": Ho+ are joins han01e0 6sing Hi*ernate, A: .est is use Criteria )uery 1%ample 8ou have parent class public class 'rgani/ation D private long org$d2 private 4ist messages2 F Child class

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

public class Message D private long message$d2 private 'rgani/ation organi/ation2 F .hbm.%ml file Gclass nameBHcom.bean.'rgani/ationH tableBH'(PA<$SA!$'<HI Gbag nameBHmessagesH inverseBHtrueH cascadeBHdeleteH la/yBHfalseHI G"ey columnBHMSPJ$-H EI Gone-to-many classBHcom.bean.MessageH EI GEbagI

GEclassI Gclass nameBHcom.bean.MessageH tableBHM1SSAP1HI Gmany-to-one nameBHorgani/ationH columnBH'(PJ$-H la/yBHfalseHEI GEclassI Pet all the messages from message table where organisation id B Gany idI Criteria )uery is : session.createCriteria*Message.class+.createAlias*Horgani/ationH&HorgH+.add*(estrictions.e) *Horg.org$dH& new 4ong*org$d+ + +.add*(estrictions.in *HstatusCodeH&status++.list*+2 you can get all the details in hibernate website. http:EEwww.hibernate.orgEhibJdocsEreferenceEenEhtmlEassociations.html

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

!he information you are posting should be related to 5ava and '(AC41 technology. <ot political. ": !hat is Hi*ernate pro43, A: .y default Hibernate creates a pro%y for each of the class you map in mapping file. !his class contain the code to invo"e 5-.C. !his class is created by hibernate using CP4$.. Cro%ies are created dynamically by sub classing your ob#ect at runtime. !he subclass has all the methods of the parent& and when any of the methods are accessed& the pro%y loads up the real ob#ect from the -. and calls the method for you. Mery nice in simple cases with no ob#ect hierarchy. !ypecasting and instance of wor" perfectly on the pro%y in this case since it is a direct subclass. ": !hat is the main a0vantage o) 6sing the hi*ernate than 6sing the sA1 , A: 3+ $f you are using Hibernate then you don0t need to learn specific S 4 *li"e oracle&mys)l+& 8ou have to user C'5' class ob#ect as a table. 6+ -on0t need to learn )uery tuning..Hibernate criteria )uery automatically tuned the )uery for best performance. 9+ 8ou can use inbuild cache for storing data :+ <o need to create own connection pool & we can use c9po . $t will give best result... ;+ -on0t need any #oin )uery which reduce performance and comple%. ,sing hibernate you have to define in bean and hbm.%ml file. =+ 8ou can add filter in Hibernate which e%ceute before you )uery fires and get the best performance >+ 1hCache is used for 6nd level cache to store all the redefind data li"e country table .. ": ho+ to create primar3 ke3 6sing hi*ernate, A: Gid nameBHuser$dH columnBH,S1(J$-H typeBHintHI Ggenerator classBHincrementHEI GEidI increment generator class automatically generate the primary "ey for you.

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

": Ho+ to E4ec6te $tore0 proce06re in Hi*ernate , A: 'ption 3: Connection con B null2 try D con B session.connection*+2 CallableStatement st B con .prepareCall*HDcall yourJsp*7&7+FH+2 st.register'utCarameter*6& !ypes.$<!1P1(+2 st.setString*3& HsomeJSe)H+2 st.e%ecute,pdate*+2 'ption 6: Gs)l-)uery nameBHselectAll1mployeesJSCH callableBHtrueHI Greturn aliasBHempH classBHemployeeHI Greturn-property nameBHempidH columnBH1MCJ$-HEI Greturn-property nameBHnameH columnBH1MCJ<AM1HEI Greturn-property nameBHaddressH columnBH1MCJA--(1SSHEI D 7 B call selectAll1mployees*+ F GEreturnI GEs)l-)ueryI code : S 4 uery s) B *S 4 uery+ session.get<amed uery*HselectAll1mployeesJSCH+2 4ist results B s).list*+2 ": +hat is 1a23 )etching in hi*ernate, A: 4a/y setting decides whether to load child ob#ects while loading the Carent 'b#ect. 8ou need to do this setting respective hibernate mapping file of the parent class. 4a/y B true *means not to load child+

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

.y default the la/y loading of the child ob#ects is true. !his ma"e sure that the child ob#ects are not loaded unless they are e%plicitly invo"ed in the application by calling getChild*+ method on parent. $n this case hibernate issues a fresh database call to load the child when getChild*+ is actually called on the Carent ob#ect. .ut in some cases you do need to load the child ob#ects when parent is loaded. 5ust ma"e the la/yBfalse and hibernate will load the child when parent is loaded from the database. 1%amples la/yBtrue *default+Address child of ,ser class can be made la/y if it is not re)uired fre)uently. la/yBfalse .ut you may need to load the Author ob#ect for .oo" parent whenever you deal with the boo" for on line boo"shop ": !hat are Hi*ernate ?etch $trategies, Y A fetching strategy is the strategy Hibernate will use for retrieving associated ob#ects if the application needs to navigate the association. Y Fetching strategy will have performance impact Y Fetch strategies may be declared in the mapping files& or over-ridden by a particular H 4 or Criteria )uery. 3pes o) ?etching $trategies F Ho+ )etching is 0one Z 5oin Z Select *default+ Z Subselect Z .atch F !hen )etching is 0one Z immediate Z la/y *default+ ": !hat are 7asca0es in hi*ernate, A: Cascades in hibernate are: save-update& delete& all& all-delete-orphan& delete-orphan and none. 3+ cascadeBHnoneH& the default& tells Hibernate to ignore the association. 6+ cascadeBHsave-updateH tells Hibernate to navigate the association when the transaction is committed and when an ob#ect is passed to save*+ or update*+ and save newly instantiated transient instances and

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

persist changes to detached instances. 9+ cascadeBHdeleteH tells Hibernate to navigate the association and delete persistent instances when an ob#ect is passed to delete*+. :+ cascadeBHallH means to cascade both save-update and delete& as well as calls to evict and loc". ;+ cascadeBHall-delete-orphanH means the same as cascadeBHallH but& in addition& Hibernate deletes any persistent entity instance that has been removed *dereferenced+ from the association *for e%ample& from a collection+. =+ cascadeBHdelete-orphanH Hibernate will delete any persistent entity instance that has been removed *dereferenced+ from the association *for e%ample& from a collection+. (ead more Hibernate AC$ for cascades. : what is the use of cascade in hbm file7 A: cascade specifies which operations should be casecaded from the parent ob#ect to the associated ob#ect. !he meaningfull values would be persist & merge& delete& saveJupdate& evict & replicate& loc" & refresh & all & deleteJorphan. : Khat is $nverse in Hibernate7 A: : 1%ample of hibernate inheritance with e%amples7

!able-per-class hierarchy !able-per-subclass !able-per-concrete class

Bapping e4amp1e )or a*1e(per(c1ass hierarch3

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

G7%ml versionBH3.?H encodingBHutf-@H 7I GL-'C!8C1 hibernate-mapping C,.4$C H-EEHibernateEHibernate Mapping -!-EE1<H Hhttp:EEhibernate.sourceforge.netEhibernate-mapping-6.?.dtdHI Ghibernate-mapping pac"ageBHe%ample.productsHI GclassnameBHC-H tableBHcdH discriminator-valueBHcdHI Gid nameBHidH typeBHintegerH unsaved-valueBH?HI Ggenerator classBHhiloHEI GEidI Gdiscriminator columnBHcdJtypeHtypeB HstringHEI Gproperty nameBHtitleHEI Gproperty nameBHartistHEI Gproperty nameBHpurchasedateH typeBHdateHEI Gproperty nameBHcostH typeBHdoubleHEI Gsubclass nameBHSpecial1ditionC-H discriminator-valueBHSpecial1ditionC-HI Gproperty nameBHnewfeaturesH typeBHstringHEI GEsubclassI Gsubclass nameBH$nternationalC-H discriminator-valueBH$nternationalC-HI Gproperty nameBHlanguagesHEI Gproperty nameBHregionHEI GEsubclassI GEclassI GEhibernate-mappingI Bapping e4amp1e )or a*1e(per(s6*c1ass
mysql> select * from cd; +--------+----------------------+--------+---------------------+------+ | id | title | artist | purchasedate | cost |

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

+--------+----------------------+--------+---------------------+------+ | 425985 | Grace Under Pressure | Rush | 2004-04-16 00:00:00 | 9.99 | | 425986 | Grace Under Pressure | Rush | 2004-04-16 00:00:00 | 9.99 | | 425987 | Grace Under Pressure | Rush | 2004-04-16 00:00:00 | 9.99 | +--------+----------------------+--------+---------------------+------+ 3 rows in set (0.00 sec) mysql> select * from secd; +--------+-------------+ | id | newfeatures | +--------+-------------+ | 425986 | Widescreen | +--------+-------------+ 1 row in set (0.00 sec) mysql> select * from icd; +--------+-----------+--------+ | id | languages | region | +--------+-----------+--------+ | 425987 | Spanish | 4 | +--------+-----------+--------+ 1 row in set (0.00 sec)

G7%ml versionBH3.?H encodingBHutf-@H 7I GL-'C!8C1 hibernate-mapping C,.4$C H-EEHibernateEHibernate Mapping -!-EE1<H Hhttp:EEhibernate.sourceforge.netEhibernatemapping-6.?.dtdHI Ghibernate-mapping pac"ageBHe%ample.productsHI Gclass nameBHC-H tableBHcdHI GidnameBHidH typeBHintegerH unsaved-valueBH?HI Ggenerator classBHhiloHEI GEidI Gproperty nameBHtitleHEI Gproperty nameBHartistHEI Gproperty nameBHpurchasedateH typeBHdateHEI Gproperty nameBHcostH typeBHdoubleHEI G#oined-subclass nameBHSpecial1ditionC-H tableBHsecdHI

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

G"ey columnBHidHEI Gproperty nameBHnewfeaturesH typeBHstringHEI GE#oined-subclassI G#oined-subclass nameBH$nternationalC-H tableBHicdHI G"ey columnBHidHEI Gproperty nameBHlanguagesHEI Gproperty nameBHregionHEI Creating Cersistent Classes GE#oined-subclassI GEclassI GEhibernate-mappingI Mapping e%ample for !able-per-concrete class G7%ml versionBH3.?H encodingBHutf-@H 7I GL-'C!8C1 hibernate-mapping C,.4$C H-EEHibernateEHibernate Mapping -!-EE1<H Hhttp:EEhibernate.sourceforge.netEhibernate-mapping-6.?.dtdHI Ghibernate-mapping pac"ageBHe%ample.productsHI GclassnameBHC-H tableBHcdH discriminator-valueBHcdHI Gid nameBHidH typeBHintegerH unsaved-valueBH?HI Ggenerator classBHhiloHEI GEidI Gproperty nameBHtitleHEI Gproperty nameBHartistHEI Gproperty nameBHpurchasedateH typeBHdateHEI Gproperty nameBHcostH typeBHdoubleHEI

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

GEclassI Gclass nameBHSpecial1ditionC-H tableBHsecdHI Gid nameBHidH typeBHintegerH unsaved-valueBH?HI Ggenerator classBHhiloHEI GEidI Gproperty nameBHtitleHEI Gproperty nameBHartistHEI Gproperty nameBHpurchasedateH typeBHdateHEI Gproperty nameBHcostH typeBHdoubleHEI Gproperty nameBHnewfeaturesH typeBHstringHEI GEclassI Gclass nameBH$nternationalC-H tableBHicdHI Gid nameBHidH typeBHintegerH unsaved-valueBH?HI Ggenerator classBHhiloHEI GEidI Gproperty nameBHtitleHEI Gproperty nameBHartistHEI Gproperty nameBHpurchasedateH typeBHdateHEI Gproperty nameBHcostH typeBHdoubleHEI Gproperty nameBHlanguagesHEI Gproperty nameBHregionHEI GEclassI GEhibernate-mappingI

Using the same example program as in the last two sections, we obtain the following rows in the three databases:

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

mysql> select * from cd; +--------+----------------------+--------+---------------------+------+ | id | title | artist | purchasedate | cost | +--------+----------------------+--------+---------------------+------+ | 458753 | Grace Under Pressure | Rush | 2004-04-16 00:00:00 | 9.99 | +--------+----------------------+--------+---------------------+------+ 1 row in set (0.00 sec)

mysql> select * from secd; +-------+----------------------+--------+--------------------+------+-----------+ |id | title | artist | purchasedate | cost |newfeatures| +-------+----------------------+--------+--------------------+------+-----------+ |491521 | Grace Under Pressure | Rush | 2004-04-16 00:00:00| 9.99 | Widescreen| +-------+----------------------+--------+--------------------+------+-----------+ 1 row in set (0.00 sec)

mysql> select * from icd; +-------+--------------------+-------+-------------------+----+---------+--------+ |id |title |artist |purchasedate |cost|languages| region | +-------+--------------------+-------+-------------------+----+---------+--------+ |524289 |Grace Under Pressure|Rush |2004-04-16 00:00:00|9.99|Spanish | 4 | +-------+--------------------+-------+-------------------+----+---------+--------+ 1 row in set (0.00 sec)

": %ne(to(%ne an0 Ban3(to(%ne e4amp1e, A: man3(to(one An ordinary association to another persistent class is declared using a many-to-one element. !he relational model is a many-to-one association: a foreign "ey in one table is referencing the primary "ey column*s+ of the target table. A typical many-to-one declaration loo"s as simple as this: Gmany-to-one nameBHproductH classBHCroductH columnBHC('-,C!J$-HEI one(to(one A one-to-one association to another persistent class is declared using a one-to-one element. e%: Gmany-to-one nameBHdepartmentH columnBHdepartmentidH classBHcom.garnai".fr.po#o.-epartmentHEI

Power By: www.garnaik.com

http://java.garnaik.com Version 1.0

": 9ocking In Hi*ernate, Hibernate is having two types of loc"ing: 'ptimistic and Cessimistic 'ptimistic Z $f you are using versioning or timestamp in your application then by default hibernate will use the loc"ing. Hibernate will always chec" the version number before updating the persistence ob#ect. Cessimistic Z 1%plicitly we can implement the loc"ing in hibernate by using the AC$. 4oc"ing of rows using S141C! F'( ,C-A!1 synta%. Ke have to set the loc" while we are loading the persistence ob#ect from the db.

Power By: www.garnaik.com

You might also like