0 оценок0% нашли этот документ полезным (0 голосов)
7 просмотров11 страниц
Hibernate is data base independent, your code will work for all ORACL,MySQL,!"L!er#er etc$. Jdbc based persistance lo ic is database dependent lo ic. Hibernate support two le#el of cache and %t will pro#ide the statistics about your )uery and database status$.
Hibernate is data base independent, your code will work for all ORACL,MySQL,!"L!er#er etc$. Jdbc based persistance lo ic is database dependent lo ic. Hibernate support two le#el of cache and %t will pro#ide the statistics about your )uery and database status$.
Hibernate is data base independent, your code will work for all ORACL,MySQL,!"L!er#er etc$. Jdbc based persistance lo ic is database dependent lo ic. Hibernate support two le#el of cache and %t will pro#ide the statistics about your )uery and database status$.
There are so many 1)Hibernate is data base independent, your code will work for all ORACL,MySQL ,!"L!er#er etc$ %n case of &'(C )uery must be data base specific$ !o hibernate based persistance lo*ic is database independent persistance lo*ic and &'(C based persistance lo*ic is database dependent lo*ic$ +)As Hibernate is set of Ob,ects , -) .o need to learn !"L lan*ua*e$/ou can treat TA(L as a Ob,ect $ Only &a#a knowled*e is need$ %n case of &'(C you need to learn !"L$ -)'ont need "uery tunin* 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 &'(C you need to tune your )ueries$ 0) /ou will *et benefit of Cache$ Hibernate support two le#el of cache$ 1irst le#el and +nd le#el$ !o you can store your data into Cache for better performance$ %n case of &'(C you need to implement your ,a#a cache $ 2)Hibernate supports "uery cache and %t will pro#ide the statistics about your )uery and database status$ &'(C .ot pro#ides any statistics$ 3)'e#elopment fast in case of Hibernate because you dont need to write )ueries 4).o need to create any connection pool in case of Hibernate$ /ou can use c-p5$ %n case of &'(C you need to write your own connection pool 6)%n the 7ml file you can see all the relations between tables in case of Hibernate$ asy readability$ 8)/ou can load your ob,ects on start up usin* la9y:false in case of Hibernate$ &'(C 'ont ha#e such support$ 15 ) Hibernate !upports automatic #ersionin* of rows but &'(C .ot$ 2.What is Hibernate? Hibernate is an open source, li*ht wei*ht Ob,ect Relational ;appin* tool to de#elop the database independent persistence lo*in in ,a#a and ,+ee based applications$ Hibernate is a pure &a#a ob,ect<relational mappin* =OR;) and persistence framework that allows you to map plain old &a#a ob,ects to relational database tables usin* =>;L) confi*uration and mappin* files$ %ts purpose is to relie#e the de#eloper from a si*nificant amount of relational data persistence<related pro*rammin* tasks 3.What is ORM ? OR; stands for ob,ect?relational mappin*, means pro#idin* the mappin* between class with table and member #ariables with columns is called OR;$ OR; is the automated persistence of ob,ects in a &a#a application to the tables in a relational database$ .hat does ORM consists of ? An OR; solution consists of the followin* four pieces@ AA% for performin* basic CRB' operations AA% to e7press )ueries referrin* to classes 1acilities to specify metadata Optimi9ation facilities @ dirty checkin*,la9y associations fetchin*
!.What are the ORM "eve"s ?
The OR; le#els are@ Aure relational =stored procedure$) Li*ht ob,ects mappin* =&'(C) ;edium ob,ect mappin* 1ull ob,ect ;appin* =composition,inheritance, polymorphism, persistence by reachability) $ #.Wh$ do $o% need ORM too"s "i&e hibernate? The main ad#anta*e of OR; like hibernate is that it can de#elop the database independent persistence lo*ic$ Apart from this, OR; pro#ides followin* benefits@ '()roved )rod%ctivit$ Hi*h<le#el ob,ect<oriented AA% Less &a#a code to write .o !"L to write '()roved )erfor(ance !ophisticated cachin* La9y loadin* a*er loadin* '()roved (aintainabi"it$ A lot less code to write '()roved )ortabi"it$ OR; framework *enerates database<specific !"L for you *.What +oes Hibernate ,i()"if$? Hibernate simplifies@ !a#in* and retrie#in* your domain ob,ects ;akin* database column and table name chan*es Centrali9in* pre sa#e and post retrie#e lo*ic Comple7 ,oins for retrie#in* related items !chema creation from ob,ect model -.What is the (ain difference between .ntit$ /eans and Hibernate ? 1)%n ntity (ean at a time we can interact with only one data (ase$ Chere as in Hibernate we can able to establishes the connections to more than One 'ata (ase$ Only thin* we need to write one more confi*uration file$ +) &( need container like Ceblo*ic, Ceb!phare but hibernate donDt nned$ %t can be run on tomcat$ -) ntity (eans does not support OOA! concepts where as Hibernate does$ 0) Hibernate supports multi le#el cachein*, where as ntity (eans doesnDt$ 2) %n Hibernate C-A5 can be used as a connection pool$ 3) Hibernate is container independent$ &( not$ 0.What are the 1ore interfaces and c"asses of Hibernate fra(ewor&? The fi#e core interfaces are used in ,ust about e#ery Hibernate application$ Bsin* these interfaces, you can store and retrie#e persistent ob,ects and control transactions$ Confi*uration class =or*$hibernate$cf* packa*e) !ession interface =or*$hibernate packa*e) !ession1actory interface =or*$hibernate packa*e) Transaction interface =or*$hibernate packa*e) "uery and Criteria interfaces =or*$hibernate packa*e) 12.What is the genera" f"ow of Hibernate co((%nication with R+/M,? The *eneral flow of Hibernate communication with R'(;! is @ Load the Hibernate confi*uration file and create confi*uration ob,ect$ %t will automatically load all hbm mappin* files because mappin* file can be confi*ured in confi*uration file$ Create session factory from confi*uration ob,ect Eet one session from this session factory Create H"L "uery 7ecute )uery to *et list containin* &a#a ob,ects$ 11.What is the need for Hibernate (a))ing fi"e? Hibernate mappin* file is used to pro#ides the mappin* between ,a#a class with table member #ariables with column names of the table$ And also we can confi*ure primary key *eneration al*orithm, relations and so on$ Typical mappin* file look as follows@ 12.What are the i()ortant tags of hibernate.cfg.3("? This file can be used to pro#ide the database information like dri#erclass name, url, database usename, database password, dialect, connection poolin* mappin* file and so on$ 1ollowin* are the important ta*s of hibernate$cf*$7ml@ 13.What ro"e does the ,ession interface )"a$ in Hibernate? The main runtime interface between a &a#a application and Hibernate The !ession interface is the primary interface used by Hibernate applications$ %t is a sin*le<threaded, short<li#ed ob,ect representin* a con#ersation between the application and the persistent store$ %t allows you to create )uery ob,ects to retrie#e persistent ob,ects$ The main function of the !ession is to offer create, read and delete operations for instances of mapped entity classes$ %nstances may e7ist in one of three states@ transient: ne#er persistent, not associated with any !ession persistent: associated with a uni)ue !ession detached: pre#iously persistent, not associated with any !ession !ession session : session1actory$open!ession=)F ,ession interface ro"e@ Craps a &'(C connection 1actory for Transaction Holds a mandatory =first<le#el) cache of persistent ob,ects, used when na#i*atin* the ob,ect *raph or lookin* up ob,ects by identifier 1.What ro"e does the ,essionFactor$ interface )"a$ in Hibernate? !ession1actorys are immutable$ The beha#iour of a !ession1actory is controlled by properties supplied at confi*uration time$ These properties are defined on n#ironment$ The application obtains !ession instances from a !ession1actory$ There is typically a sin*le !ession1actory for the whole applicationGreated durin* application initiali9ation$ The !ession1actory caches *enerate !"L statements and other mappin* metadata that Hibernate uses at runtime$ %t also holds cached data that has been read in one unit of work and may be reused in a future unit of work %mplementors must be threadsafe$ !ession1actory session1actory : confi*uration$build!ession1actory=)F 1!.What are the (ost co((on wa$s to s)ecif$ the Hibernate config%ration )ro)erties? The most common methods of Hibernate confi*uration are@ Aro*rammatic confi*uration (y usin* setAroperty=<) method of or*$hibernate$cf*$Confi*uration$ >;L confi*uration =hibernate$cf*$7ml) (y usin* $properties file (y Bsin* annotaions$=from Hibernate -$- on words) 1#.How do $o% (a) 4ava Objects with +atabase tab"es? 1irst we need to write &a#a domain ob,ects =beans with setter and *etter)$ Crite hbm$7ml, where we map ,a#a class to table and database columns to &a#a class #ariables$ .3a()"e @ Hhibernate<mappin*I Hclass name:Jcom$dur*asoft$mployee(eanJ table:J;ALO/JI Hid name:Gidcolume:GdI Hproperty name:JenameJ column:J.A;J len*th:J+22J not<null:JtrueJ type:J,a#a$lan*$!trin*J?I Hproperty name:JaddressJ column:JA''RJ len*th:J+22J not<null:JtrueJ type:J,a#a$lan*$!trin*J?I H?classI H?hibernate<mappin*I 1*.How do $o% define se5%ence generated )ri(ar$ &e$ a"gorith( in hibernate? (y usin* HidI, H*eneratorI ta*s we can confi*ure the primary key and primary key *eneration al*orithm$ .3a()"e@< Hid name:JuseridJ column:JB!RK%'J type:J,a#a$lan*$Lon*JI H*enerator class:Jse)uenceJI Hparam name:JtableJI!"K.A;H?paramI H*eneratorI H?idI 1-.What is co()onent (a))ing in Hibernate? A component is an ob,ect sa#ed as a #alue, not as a reference A component can be sa#ed directly without needin* to declare interfaces or identifier properties Re)uired to define an empty constructor !hared references not supported 10 . +ifference between get1%rrent,ession67 and o)en,ession67 in Hibernate ? *etCurrent!ession=) @ Obtains the current session$ The Jcurrent sessionJ refers to a Hibernate !ession bound by Hibernate behind the scenes, to the transaction scope$ A !ession is opened when *etCurrent!ession=) is called for the first time and closed when the transaction ends$ %t is also flushed automatically before the transaction commits$ /ou can call *etCurrent!ession=) as often and anywhere you want as lon* as the transaction runs$ Only the !ession that you obtained with sf$*etCurrent!ession=) is flushed and closed automatically$ open!ession=) @ %f you decide to use mana*e the !ession yourself the *o for sf$open!ession=) , you ha#e to flush=) and close=) it$ %t does not flush and close=) automatically$ 7ample @ Transaction t7 :session$ber*inTransaction=)F !ession session : factory$open!ession=)F try L t7$be*in=)F ?? 'o some work session$create"uery=$$$)F session$persist=$$$)F session$flush=)F ?? 7tra work you need to do t7$commit=)F M catch =Runtime7ception e) L t7$rollback=)F throw eF ?? or display error messa*e M finally L session$close=)F ?? 7tra work you need to do M 22.What are the t$)es of Hibernate instance states ? Three types of instance states@ Transient <The instance is not associated with any persistence conte7t Aersistent <The instance is associated with a persistence conte7t 'etached <The instance was associated with a persistence conte7t which has been closed currently not associated 21.What are the t$)es of inheritance (ode"s in Hibernate? There are three types of inheritance models in Hibernate@ Table per class hierarchy Table per subclass Table per concrete class 22.What is Hibernate Q%er$ 8ang%age 6HQ87? Hibernate "uery Lan*ua*e is )uery lan*ua*e which is used to de#elop the data independent )uery lan*ua*e in the application$ This H"L )ueries are not related to any database$ Hibernate offers a )uery lan*ua*e that embodies a #ery powerful and fle7ible mechanism to )uery, store, update, and retrie#e ob,ects from a database$ This lan*ua*e, the Hibernate )uery Lan*ua*e =H"L), is an ob,ect< oriented e7tension to !"L$ 23.What are the wa$s to e3)ress joins in HQ8? H"L pro#ides four ways of e7pressin* =inner and outer) ,oins@< An implicit association ,oin An ordinary ,oin in the 1RO; clause A fetch ,oin in the 1RO; clause$ A theta-style ,oin in the CHR clause$ 2 . 9ransaction with )"ain 4+/1 in Hibernate ? %f you donDt ha#e &TA and donDt want to deploy it alon* with your application, you will usually ha#e to fall back to &'(C transaction demarcation$ %nstead of callin* the &'(C AA% you better use HibernateDs Transaction and the built<in session<per<re)uest functionality@ To enable the thread<bound strate*y in your Hibernate confi*uration@ set hibernate$transaction$factoryKclass to or*$hibernate$transaction$&'(CTransaction1actory set hibernate$currentKsessionKconte7tKclass to thread !ession session : factory$open!ession=)F Transaction t7 : nullF try L t7 : session$be*inTransaction=)F ?? 'o some work session$load=$$$)F session$persist=$$$)F t7$commit=)F ?? 1lush happens automatically M catch =Runtime7ception e) L t7$rollback=)F throw eF ?? or display error messa*e M finally L session$close=)F M 2! . What are the genera" considerations or best )ractices for defining $o%r Hibernate )ersistent c"asses? 1$/ou must ha#e a default no<ar*ument constructor for your persistent classes and there should be *et>>>=)and set>>>=) methods for all your persistable instance #ariables$ +$/ou should implement the e)uals=) and hashCode=) methods based on your business key and it is important not to use the id field in your e)uals=) and hashCode=) definition if the id field is a surro*ate key =i$e$ Hibernate mana*ed identifier)$ This is because the Hibernate only *enerates and sets the field when sa#in* the ob,ect$ -$ %t is recommended to implement the !eriali9able interface$ This is potentially useful if you want to mi*rate around a multi<processor cluster$ 0$The persistent class should not be final because if it is final then la9y loadin* cannot be used by creatin* pro7y ob,ects$ 2# . +ifference between session.%)date67 and session."oc&67 in Hibernate ? The session$update method is used to update the persistence ob,ect in the in the database$ The session$lock=) method simply reattaches the ob,ect to the session without checkin* or updatin* 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$sa#eOrBpdate=)$ Bse session$lock=) 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 o#erwritin* all the columns that would ha#e chan*ed later on within the same transaction$ 2*.What are the 1o""ection t$)es in Hibernate ? !et List Array ;ap (a* 2-.What is the difference between sorted and ordered co""ection in hibernate? sorted co""ection vs. order co""ection @< sorted collection order collection A sorted collection is sortin* a collection by utili9in* the sortin* features pro#ided by the &a#a collections framework$ The sortin* occurs in the memory of &N; which runnin* Hibernate, after the data bein* read from database usin* ,a#a comparator$ Order collection is sortin* a collection by specifyin* the order<by clause for sortin* this collection when retrie#al$ %f your collection is not lar*e, it will be more efficient way to sort it$ %f your collection is #ery lar*e, it will be more efficient way to sort it $ 20.What are the wa$s to e3)ress joins in HQ8? H"L pro#ides four ways of e7pressin* =inner and outer) ,oins@< An implicit association ,oin An ordinary ,oin in the 1RO; clause A fetch ,oin in the 1RO; clause$ A theta-style ,oin in the CHR clause$ 32.What do $o% (ean b$ :a(ed ,Q8 5%er$? .amed !"L )ueries are defined in the mappin* 7ml document and called where#er re)uired$ .3a()"e; Hs)l<)uery name : JempdetailsJI Hreturn alias:JempJ class:Jcom$dur*asoft$mployeeJ?I !LCT emp$;AK%' A! Lemp$empidM, emp$;AKA''R!! A! Lemp$addressM, emp$;AK.A; A! Lemp$nameM 1RO; mployee ;A CHR emp$.A; L%O @name H?s)l<)ueryI %n#oke .amed "uery @ List people : session$*et.amed"uery=JempdetailsJ) $set!trin*=JTom(radyJ, name) $set;a7Results=25) $list=)F -1$How do you in#oke !tored AroceduresG Hs)l<)uery name:JselectAllmployeesK!AJ callable:JtrueJI Hreturn alias:JempJ class:JemployeeJI Hreturn<property name:JempidJ column:J;AK%'J?I Hreturn<property name:JnameJ column:J;AK.A;J?I Hreturn<property name:JaddressJ column:J;AKA''R!!J?I L G : call selectAllmployees=) M H?returnI H?s)l<)ueryI 32..3)"ain 1riteria A<' The interface or*$hibernate$Criteria represents a )uery a*ainst a particular persistent class$ The !ession is a factory for Criteria instances$ Criteria is a simplified AA% for retrie#in* entities by composin* Criterion ob,ects$ This is a #ery con#enient approach for functionality like JsearchJ screens where there is a #ariable number of conditions to be placed upon the result set$ .3a()"e @ List employees : session$createCriteria=mployee$class) $add=Restrictions$like=JnameJ, JaPJ) ) $add=Restrictions$like=JaddressJ, J(ostonJ)) $addOrder=Order$asc=JnameJ) ) $list=)F 33.What? the difference between "oad67 and get67? load=) *et=) Only use the load=) method if you are sure that the ob,ect e7ists$ %f you are not sure that the ob,ect e7ists, then use one of the *et=) methods$ load=) method will throw an e7ception if the uni)ue id is not found in the database$ *et=) method will return null if the uni)ue id is not found in the database$ load=) ,ust returns a pro7y by default and database wonG be hit until the pro7y is first in#oked$ *et=) will hit the database immediately$ 3.What is the difference between and (erge and %)date ? Bse update=) if you are sure that the session does not contain an already persistent instance with the same identifier, and mer*e=) if you want to mer*e your modifications at any time without consideration of the state of the session$ 3!.+efine cascade and inverse o)tion in one=(an$ (a))ing? cascade < enable operations to cascade to child entities$ cascade:JallQnoneQsa#e<updateQdeleteQall<delete<orphanJ in#erse < mark this collection as the Jin#erseJ end of a bidirectional association$ in#erse:JtrueQfalseJ ssentially Jin#erseJ indicates which end of a relationship should be i*nored, so when persistin* a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents areG 3#.+efine Hibernate9e()"ate? or*$sprin*framework$orm$hibernate$HibernateTemplate is a helper class which pro#ides different methods for )ueryin*?retrie#in* data from the database$ %t also con#erts checked Hibernate7ceptions into unchecked 'ataAccess7ceptions$ 3*.What are the benefits does Hibernate9e()"ate )rovide? The benefits of HibernateTemplate are @ HibernateTemplate, a !prin* Template class simplifies interactions with Hibernate !ession$ Common functions are simplified to sin*le method calls$ !essions are automatically closed$ 7ceptions are automatically cau*ht and con#erted to runtime e7ceptions$ 3-. How do $o% switch between re"ationa" databases witho%t code changes? Bsin* Hibernate !"L 'ialects , we can switch databases$ Hibernate will *enerate appropriate h)l )ueries based on the dialect defined$ 30.'f $o% want to see the Hibernate generated ,Q8 state(ents on conso"e> what sho%"d we do? (y usin* GhowKs)lproperty of the hibernate confi*uration file %n Hibernate confi*uration file set as follows@ Hproperty name:JshowKs)lJItrueH?propertyI 2.What are derived )ro)erties? The properties that are not mapped to a column, but calculated at runtime by e#aluation of an e7pression are called deri#ed properties$ The e7pression can be defined usin* the formula attribute of the element$ 1.+efine cascade and inverse o)tion in one=(an$ (a))ing? cascade < enable operations to cascade to child entities$ cascade:JallQnoneQsa#e<updateQdeleteQall<delete<orphanJ in#erse < mark this collection as the Jin#erseJ end of a bidirectional association$ in#erse:JtrueQfalseJ ssentially Jin#erseJ indicates which end of a relationship should be i*nored, so when persistin* a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents areG 2 . .3)"ain abo%t transaction fi"e? Transactions denote a work file which can sa#e chan*es made or re#ert back the chan*es$ A transaction can be started by session$be*inTransaction=) and it uses &'(C connection, COR(A or &TA$ Chen this session starts se#eral transactions may occur$ 3 . +ifference between session.save67 > session.saveOr?)date67 and session.)ersist67? All methods are used to store the data in to database session$sa#e=) @ sa#e=) method u!a#e does an insert and will fail if the primary key is already persistent$ session$sa#eOrBpdate=) @ sa#eOrBpdate=) insert the data in the database if that primary key data not a#ailable and it update the data if primary key data not a#ailabt session$persist=) @it is the same like session$sa#e=)$ (ut session$sa#e=) return !eriali9able ob,ect but session$persist=) return #oid$ 1or 7ample @ if you do @< !ystem$out$println=session$sa#e=)uestion))F This will print the *enerated primary key$ if you do @< !ystem$out$println=session$persist=)uestion))F Compile time error because session$persist=) return #oid$ . .3)"ain abo%t the id fie"d? This id field is used to confi*ure the primary key in the mappin* file, and also we can confi*ure primary key *eneration al*orithm$ !.What is the %se of d$na(ic=insert and d$na(ic=%)date attrib%tes in a c"ass (a))ing? Criteria is a simplified AA% for retrie#in* entities by composin* Criterion ob,ects$ This is a #ery con#enient approach for functionality like JsearchJ screens where there is a #ariable number of conditions to be placed upon the result set$ dynamic<update =defaults to false)@ !pecifies that BA'AT !"L should be *enerated at runtime and contain only those columns whose #alues ha#e chan*ed dynamic<insert =defaults to false)@ !pecifies that %.!RT !"L should be *enerated at runtime and contain only the columns whose #alues are not null$ #.What is a%to(atic dirt$ chec&ing? Automatic dirty checkin* is a feature that sa#es us the effort of e7plicitly askin* Hibernate to update the database when we modify the state of an ob,ect inside a transaction$ *.What are 1a""bac& interfaces? Callback interfaces allow the application to recei#e a notification when somethin* interestin* happens to an ob,ectGor e7ample, when an ob,ect is loaded, sa#ed, or deleted$ Hibernate applications donDt need to implement these callbacks, but theyDre useful for implementin* certain kinds of *eneric functionality$ -.What is Hibernate )ro3$? The pro7y attribute enables la9y initiali9ation of persistent instances of the class$ Hibernate will initially return CEL%( pro7ies which implement the named interface$ The actual persistent ob,ect will be loaded when a method of the pro7y is in#oked$ 0.How can Hibernate be config%red to access an instance variab"e direct"$ and not thro%gh a setter (ethod ? (y mappin* the property with access:JfieldJ in Hibernate metadata$ This forces hibernate to bypass the setter method and access the instance #ariable directly while initiali9in* a newly loaded ob,ect$ !2.How can a who"e c"ass be (a))ed as i((%tab"e? ;ark the class as mutable:JfalseJ ='efault is true),$ This specifies that instances of the class are =not) mutable$ %mmutable classes, may not be updated or deleted by the application$ !1 . .3)"ain abo%t trans)arent )ersistence of Hibernate? Transparent persistence is pro#ided for Alain old &a#a ob,ects or AO&Os$ 1or proper functionin* of the applications importance should be *i#en to the methods e)uals =) and hash Code methods =)$ %t has a re)uirement which should be strictly followed in the applications which is a no<ar*ument constructor$ !2 . .3)"ain abo%t the dirt$ chec&ing feat%re of Hibernate? 'irty checkin* feature of the Hibernate allows users or de#elopers to a#oid time consumin* data base write actions$ This feature makes necessary updations and chan*es to the fields which re)uire a chan*e, remainin* fields are left unchan*ed or untouched$ !3 . What is the effect when a transient (a))ed object is )assed onto a ,essions save? Chen a !essions sa#e =) is passed to a transient mapped ob,ect it makes the method to become more persistent$ Earba*e collection and termination of the &a#a #irtual machine stays as lon* as it is deleted e7plicitly$ %t may head back to its transient state$ ! . .3)"ain abo%t add1"ass f%nction? This function translates a &a#a class name into file name$ This translated file name is then loaded as an input stream from the &a#a class loader$ This addClass function is important if you want efficient usa*e of classes in your code$