203
Hibernate Interview Questions and Answers 1. What is Hibernate Framework? Object-relational mapping or ORM is the programming technique to map application domain model objects to the relational database tables. Hibernate is java based ORM tool that provides framework for mapping application domain objects to the relational database tables and vice versa. Hibernate provides reference implementation of Java Persistence API, that makes it a great choice as ORM tool with benefits of loose coupling. We can use Hibernate persistence API for CRUD operations. Hibernate framework provide option to map plain old java objects to traditional database tables with the use of JPA annotations as well as XML based configuration. Similarly hibernate configurations are flexible and can be done from XML configuration file as well as programmatically. For a quick overview of hibernate framework usage, you can go through Hibernate Beginners Tutorial . 2. What is Java Persistence API (JPA)? Java Persistence API (JPA) provides specification for managing the relational data in applications. Current JPA version 2.1 was started in July 2011 as JSR 338. JPA 2.1 was approved as final on 22 May 2013. JPA specifications is defined with annotations in javax.persistence package. Using JPA annotation helps us in writing implementation independent code. 3. What are the important benefits of using Hibernate Framework?

HibernateInterviewQuestions&Answers

  • Upload
    phani

  • View
    230

  • Download
    5

Embed Size (px)

DESCRIPTION

hib int

Citation preview

Hibernate Interview Questions and Answers1. What is Hibernate Framework?Object-relational mapping or ORM s the programmng technque to map appcaton doman mode ob|ects to the reatona database tabes. Hbernate s |ava based ORM too that provdes framework for mappng appcaton doman ob|ects to the reatona database tabes and vce versa.Hbernate provdes reference mpementaton of |ava Persstence API, that makes t a great choce as ORM too wth benets of oose coupng. We can use Hbernate persstence API for CRUD operatons. Hbernate framework provde opton to map pan od |ava ob|ects to tradtona database tabes wth the use of |PA annotatons as we as XML based conguraton.Smary hbernate conguratons are exbe and can be done from XML conguraton e as we as programmatcay. For a quck overvew of hbernate framework usage, you can go through Hbernate Begnners Tutora.2. What is Java Persistence API (JPA)?|ava Persstence API (|PA) provdes speccaton for managng the reatona data n appcatons. Current |PA verson 2.1 was started n |uy 2011 as |SR 338. |PA 2.1 was approved as na on 22 May 2013.|PA speccatons s dened wth annotatons n |avax.persstence package. Usng |PA annotaton heps us n wrtng mpementaton ndependent code.3. What are the important beneits o !sin" Hibernate Framework?Some of the mportant benets of usng hbernate framework are:A. Hbernate emnates a the boer-pate code that comes wth |DBC and takes care of managng resources, so we can focus on busness ogc.B. Hbernate framework provdes support for XML as we as |PA annotatons, that makes our code mpementaton ndependent.C. Hbernate provdes a powerfu query anguage (HOL) that s smar to SOL. However, HOL s fuy ob|ect-orented and understands concepts ke nhertance, poymorphsm and assocaton.D. Hbernate s an open source pro|ect from Red Hat Communty and used wordwde. Ths makes t a better choce than others because earnng curve s sma and there are tons of onne documentatons and hep s easy avaabe n forums.E. Hbernate s easy to ntegrate wth other |ava EE frameworks, ts sopopuar that Sprng Framework provdes but-n support for ntegratng hbernate wth Sprng appcatons.F. Hbernate supports azy ntazaton usng proxy ob|ects and perform actua database queres ony when ts requred.G. Hbernate cache heps us n gettng better performance.H. For database vendor specc feature, hbernate s sutabe because we can aso execute natve sq queres.Overa hbernate s the best choce n current market for ORM too, t contans a the features that you w ever need n an ORM too.#. What are the a$vanta"es o Hibernate over J%&'?Some of the mportant advantages of Hbernate framework over |DBC are:A. Hbernate removes a ot of boer-pate code that comes wth |DBC API, the code ooks more ceaner and readabe.B. Hbernate supports nhertance, assocatons and coectons. These features are not present wth |DBC API.C. Hbernate mpcty provdes transacton management, n fact most of the queres cant be executed outsde transacton. In |DBC API, we need to wrte code for transacton management usng commt and roback. Read more at |DBC Transacton Management.D. |DBC API throws SOLExcepton that s a checked excepton, so we needto wrte a ot of try-catch bock code. Most of the tmes ts redundant n every |DBC ca and used for transacton management. Hbernate wraps |DBC exceptons and throw |DBCExcepton or HbernateExcepton un-checked excepton, so we dont need to wrte code to hande t. Hbernate but-n transacton management removes the usage of try-catch bocks.E. Hbernate Ouery Language (HOL) s more ob|ect orented and cose to |ava programmng anguage. For |DBC, we need to wrte natve sq queres.F. Hbernate supports cachng that s better for performance, |DBC queres are not cached hence performance s ow.G. Hbernate provde opton through whch we can create database tabes too, for |DBC tabes must exst n the database.H. Hbernate conguraton heps us n usng |DBC ke connecton as we as |NDI DataSource for connecton poo. Ths s very mportant feature n enterprse appcaton and competey mssng n |DBC API.I. Hbernate supports |PA annotatons, so code s ndependent of mpementaton and easy repaceabe wth other ORM toos. |DBC code s very tghty couped wth the appcaton.(. )ame some important interaces o Hibernate ramework?Some of the mportant nterfaces of Hbernate framework are:A. SessionFactory (org.hibernate.SessionFactory): SessonFactory s an mmutabe thread-safe cache of comped mappngsfor a snge database. We need to ntaze SessonFactory once and thenwe can cache and reuse t. SessonFactory nstance s used to get the Sesson ob|ects for database operatons.B. Session (org.hibernate.Session): Sesson s a snge-threaded, short-ved ob|ect representng a conversaton between the appcaton and the persstent store. It wraps |DBC |ava.sq.Connectonand works as a factory for org.hbernate.Transacton. We shoud open sesson ony when ts requred and cose t as soon as we are done usng t. Sesson ob|ect s the nterface between |ava appcaton code and hbernate framework and provde methods for CRUD operatons.C. Transaction (org.hibernate.Transaction): Transacton s a snge-threaded, short-ved ob|ect used by the appcaton to specfy atomc unts of work. It abstracts the appcaton from the underyng |DBC or |TA transacton. A org.hbernate.Sesson mght span mutpe org.hbernate.Transacton n some cases.*. What is hibernate coni"!ration i+e?Hbernate conguraton e contans database specc conguratons and used to ntaze SessonFactory. We provde database credentas or |NDI resource nformaton n the hbernate conguraton xm e. Some other mportant parts of hbernate conguraton e s Daect nformaton, so that hbernate knows the database type and mappng e or cass detas.,. What is hibernate mappin" i+e?Hbernate mappng e s used to dene the entty bean eds and database tabe coumn mappngs. We know that |PA annotatons can be used for mappng but sometmes XML mappng e comes handy when we are usng thrd party casses and we cant use annotatons.-. )ame some important annotations !se$ or Hibernate mappin"?Hbernate supports |PA annotatons and t has some other annotatons n org.hbernate.annotatonspackage. Some of the mportant |PA and hbernate annotatons used are:A. javax.persistence.Entity: Used wth mode casses to specfy thatthey are entty beans.B. javax.persistence.Table: Used wth entty beans to dene the correspondng tabe name n database.C. javax.persistence.Access: Used to dene the access type, ether ed or property. Defaut vaue s ed and f you want hbernate to use getter/setter methods then you need to set t to property.D. javax.persistence.I: Used to dene the prmary key n the entty bean.E. javax.persistence.EmbeeI: Used to dene composte prmary key n the entty bean.F. javax.persistence.!ol"mn: Used to dene the coumn name n database tabe.G. javax.persistence.#enerate$al"e: Used to dene the strategy to be used for generaton of prmary key. Used n con|uncton wth |avax.persstence.GeneratonType enum.H. javax.persistence.OneToOne: Used to dene the one-to-one mappng between two entty beans. We have other smar annotatons as OneToMany, ManyToOne and ManyToManyI. org.hibernate.annotations.!ascae: Used to dene the cascadng between two entty beans, used wth mappngs. It works n con|uncton wth org.hbernate.annotatons.CascadeType|. javax.persistence.%rimary&ey'oin!ol"mn: Used to dene the property for foregn key. Used wthorg.hbernate.annotatons.GenercGenerator and org.hbernate.annotatons.ParameterHere are two casses showng usage of these annotatons.Empoyee.|ava123456789101package com.journaldev.hibernate.model; import javax.persistence.Access;import javax.persistence.AccessType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.neTone;import javax.persistence.Table; 11213141516171819202122232425262import org.hibernate.annotations.Cascade; !Entity!Table"name $ %E&'()EE%*!Access"value$AccessType.+IE(,*public class Employee - !Id!GeneratedValue"strategy $ GenerationType.I,E.TIT)*!Column"name $ %emp/id%*private long id; !Column"name $ %emp/name%*private 0tring name; !neTone"mapped1y $ %employee%*!Cascade"value $ org.hibernate.annotations.CascadeType.A((*private Address address; 22getter setter methods37282930313233Address.|ava1234567891011121package com.journaldev.hibernate.model; import javax.persistence.Access;import javax.persistence.AccessType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.neTone;import javax.persistence.'rimary4ey5oinColumn;import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator;import org.hibernate.annotations.'arameter; 31415161718192021222324252627282!Entity!Table"name $ %A,,6E00%*!Access"value$AccessType.+IE(,*public class Address - !Id!Column"name $ %emp/id%7 uni8ue $ true7 nullable $ 9alse*!GeneratedValue"generator $ %gen%*!GenericGenerator"name $ %gen%7 strategy $ %9oreign%7 parameters $ - !'arameter"name $ %property%7 value $ %employee%* 3*private long id; !Column"name $ %address/line:%*private 0tring address(ine:; !neTone!'rimary4ey5oinColumnprivate Employee employee; 22getter setter methods39303132333435.. What is Hibernate /essionFactor0 an$ how to coni"!re it?SessonFactory s the factory cass used to get the Sesson ob|ects. SessonFactory s responsbe to read the hbernate conguraton parametersand connect to the database and provde Sesson ob|ects. Usuay an appcaton has a snge SessonFactory nstance and threads servcng cent requests obtan Sesson nstances from ths factory.The nterna state of a SessonFactory s mmutabe. Once t s created ths nterna state s set. Ths nterna state ncudes a of the metadata about Ob|ect/Reatona Mappng.SessonFactory aso provde methods to get the Cass metadata and Statstcs nstance to get the stats of query executons, second eve cache detas etc.11. Hibernate /essionFactor0 is threa$ sae?Interna state of SessonFactory s mmutabe, so ts thread safe. Mutpe threads can access t smutaneousy to get Sesson nstances.11. What is Hibernate /ession an$ how to "et it?Hbernate Sesson s the nterface between |ava appcaton ayer and hbernate. Ths s the core nterface used to perform database operatons. Lfecyce of a sesson s bound by the begnnng and end of a transacton.Sesson provde methods to perform create, read, update and deete operatons for a persstent ob|ect. We can execute HOL queres, SOL natve queres and create crtera usng Sesson ob|ect.12. Hibernate /ession is threa$ sae?Hbernate Sesson ob|ect s not thread safe, every thread shoud get ts own sesson nstance and cose t after ts work s nshed.13. What is $ierence between open/ession an$ "et'!rrent/ession?Hbernate SessonFactory getCurrentSesson() method returns the sesson bound to the context. But for ths to work, we need to congure t n hbernate conguraton e. Snce ths sesson ob|ect beongs to the hbernate context, we dont need to cose t. Once the sesson factory s cosed, ths sesson ob|ect gets cosed.1;property name$%hibernate.current/session/context/class%;2versionbehind?Hibernate uses a so"histicated algorithm to determine an efficient ordering that avoids database foreign key constraint violations but is still sufficiently "redictable to the user. This feature is called transactional write5behind.$".What are Callback interfaces?,allback interfaces allow the a""lication to receive a notification when something interesting ha""ens to an ob)ectIfor e$am"le, when an ob)ect is loaded, saved, or deleted. Hibernate a""lications dont need to im"lement these callbacks, but theyre useful for im"lementing certain kinds of generic functionality.$#.What are the types of Hibernate instance states ?Three ty"es of instance states+ Transient 5The instance is not associated with any "ersistence conte$t Persistent 5The instance is associated with a "ersistence conte$t .etached 5The instance was associated with a "ersistence conte$t which has been closed J currently not associated$$.What are the differences between E46 #./ D HibernateHibernate Gs E&4 K.L +5Hibernate-+, ./0 )essionJ,ache or collection of loaded ob)ects relating to a single unit of work Aersistence Conte+t5#et of entities that can be managed by a given Entity(anager is defined by a "ersistence unitPeop+e who rea$ this5 a+so rea$H95451 &nterview 3uestions4)0 Butorial!y0aces E+amplesHibernate Es i6atisBibco &nterview 3uestions1(oclet 5nnotations used to su""ort Attribute 'riented Programming 4ava %./ 5nnotations used to su""ort Attribute 'riented Programming (efines H32 for e$"ressing /ueries to the database(efines E46 32 for e$"ressing /ueries )upports Entity elationships through ma""ing files and annotations in &ava.oc )upport Entity elationships through &ava M.L annotationsArovides a Aersistence !anager 5A& e$"osed via the #ession, 7uery, ,riteria, and Transaction API Arovides and Entity !anager &nterface for managing ,R-. o"erations for an Entity Arovides callback support through lifecycle, interce"tor, and validatable interfaces Arovides callback support through Entity 3istener and ,allback methods Entity elationships are unidirectional. 4idirectional relationshi"s are im"lemented by two unidirectional relationshi"s Entity elationships are bidirectional or unidirectional$%.What are the types of inheritance models in Hibernate?There are three ty"es of inheritance models in Hibernate+ Table "er class hierarchy Table "er subclass Table "er concrete class1/ What is benefit of using O23 tools??he main a$vanta"e o 6AB +ike hibernate is that it shie+$s $eve+opers rom mess0 /;4. Apart romthis5 6AB provi$es o++owin" beneitsH Improve$ pro$!ctivit0 Hi"h9+eve+ ob>ect9oriente$ API 4ess Java co$e to write )o /;4 to write Improve$ perormance /ophisticate$ cachin" 4a=0 +oa$in"P 2a"er +oa$in" Improve$ maintainabi+it0 A +ot +ess co$e to write Improve$ portabi+it0 6AB ramework "enerates $atabase9speciic /;4 or 0o!.4/ What are the most common methods of Hibernate configuration??he most common metho$s o Hibernate coni"!ration areHPro"rammatic coni"!rationCB4 coni"!ration (hibernate.c".3m+)./ What are the &ore interfaces are of Hibernate framewor(??he ive core interaces are !se$ in >!st abo!t ever0 Hibernate app+ication. 7sin" these interaces50o! can store an$ retrieve persistent ob>ects an$ contro+ transactions. /ession interace /essionFactor0 interace 'oni"!ration interace ?ransaction interace ;!er0 an$ 'riteria interace5/ What role does the ession interface pla# in Hibernate??he /ession interace is the primar0 interace !se$ b0 Hibernate app+ications. It is a sin"+e9threa$e$5short9+ive$ob>ect representin"aconversationbetweentheapp+icationan$thepersistent store./ession isnot threadsafe sowesho!+$not sharesamesessionbetweenm!+tip+ethrea$s. Ita++ows 0o! to create ects to retrieve persistent ob>ects. /ession session L sessionFactor0.open/ession()S /ession interace ro+eH Wraps a J%&' connection Factor0 or ?ransactionHo+$s a man$ator0 (irst9+eve+) cache o persistent ob>ects5 !se$ when navi"atin" theob>ect "raph or +ookin" !p ob>ects b0 i$entiier6/ What role does the ession$actor# interface pla# in Hibernate?App+ication obtains /ession instances rom a /essionFactor0. ?here is t0pica++0 a singleession$actor# or the who+e app+ication create$ $!rin" app+ication initia+i=ation. ?he/essionFactor0 caches "enerate /;4 statements an$ other mappin" meta$ata that Hibernate !sesat r!ntime. It a+so ho+$s cache$ $ata that has been rea$ in one !nit o work an$ ma0 be re!se$ in a!t!re !nit o work /essionFactor0 sessionFactor0 L coni"!ration.b!i+$/essionFactor0()S7/ What is the general flow of Hibernate communication with 2D,3??he "enera+ +ow o Hibernate comm!nication with A%&B/ is H4oa$the Hibernate coni"!ration i+e an$ createconi"!rationob>ect.Itwi++ a!tomatica++0+oa$ a++ hbm mappin" i+es 'reate session actor0 rom coni"!ration ob>ect:et one session rom this session actor0'reate H;4 ;!er023ec!te ects8/ What is Hibernate Quer# !anguage )HQ!*?Hibernate oers a ects rom a $atabase. ?his +an"!a"e5 the Hibernate ect9oriente$ e3tension to /;4.9/ What:s the difference between load)* and get)*?+oa$() vs. "et() H9load)* 6n+0 !se the +oa$() metho$ i 0o! are s!re that the ob>ect e3ists. +oa$() metho$ wi++ throw an e3ception i the !ni!st ret!rns a pro30 b0 $ea!+t an$ $atabase won8t be hit !nti+ the pro30 is irst invoke$. get)* I 0o! are not s!re that the ob>ect e3ists5 then !se one o the "et() metho$s. "et() metho$ wi++ ret!rn n!++ i the !niects. ?his is a ver0 convenient approach or !nctiona+it0 +ike YsearchY screens where there is a variab+e n!mber o con$itions to be p+ace$ !pon the res!+t set.23amp+e H4ist emp+o0ees L session.create'riteria(2mp+o0ee.c+ass).a$$(Aestrictions.+ike(YnameY5 Ya[Y) ).a$$(Aestrictions.+ike(Ya$$ressY5 Y&ostonY)).a$$6r$er(6r$er.asc(YnameY) ).+ist()S16/ What are the benefits does HibernateAemplate provide?or".sprin"ramework.orm.hibernate.Hibernate?emp+ate is a he+per c+ass which provi$es $ierent metho$s or vm memor05 it can throw 6!t o Bemor0 error. Order collection 6r$er co++ection is sortin" a co++ection b0 speci0in" the order%b# clause in ect to an0 other session b0 ca++in" either update"* or saverDpdate"* metho$ on that session.4./ What is automatic dirt# chec(ing?A!tomatic $irt0 checkin" is a eat!re that saves !s the eort o e3p+icit+0 askin" Hibernate to !p$ate the $atabase when we mo$i0 the state o an ob>ect insi$e a transaction.45/ ample of Hibernate transaction management?A or".hibernate./ession is $esi"ne$ to represent a sin"+e !nit o work (a sin"+e atmoic piece o work to be perorme$./amp+e co$e o han$+in" transaction rom hibernate session./ession session L Hibernate7ti+."et/essionFactor0()."et'!rrent/ession()Ssession/beginAransaction)*F2vent the2vent L new 2vent()Sthe2vent.set?it+e(tit+e)Sthe2vent.set%ate(the%ate)Ssession.save(the2vent)Ssession/getAransaction)*/commit)*F46/ How to implement Optimistic loc(ing in Database?Wo! can imp+ement optimistic +ocks in 0o!r %& tab+e in this wa0 (?his is how optimistic +ockin" is $one in Hibernate)H9 A$$ inte"er YversionY co+!mn to 0o!r tab+e.9 Increase va+!e o this co+!mn with each !p$ate o correspon$in" row.9 ?o obtain +ock5 >!st rea$ YversionY va+!e o row.9 A$$ Yversion L obtaine$OversionY con$ition to where c+a!se o 0o!r !p$ate statement.9 @eri0 n!mber o aecte$ rows ater !p$ate. I no rows were aecte$ 9 someone has a+rea$0 mo$iie$ 0o!r entr0.Wo!r !p$ate sho!+$ +ook +ike UPDATE mytable SET name'Andy'! "ersion# $%E&E id' and "ersion()26. What is Second level Cache and QueryCache in Hibernate?Second level Cache is maintained at SessionFactory level and It improves performance by saving few databaseround trip. Another worth noting point is that second level cache is available to whole application rather than any particular session. QueryCache actually stores result of sql query for future calls. Query cache can be used along with second level cache for improved performance. Hibernate support various open source caching solution to implement Query cache e.g. hCache.http://|avadecodedquestons.bogspot.n/2011/12/hbernate-ntervew-questons.htm1) What is Hibernate?Hibernate is a power!+5 hi"h perormance ob>ectPre+ationa+ persistence an$ ectPre+ationa+ persistence it even re$!ces the46'. ?erformance > Han$9co$e$ persistence provi$e$ "reater perormance than a!tomate$ one. &!t this is not tr!e a++ the times. &!t in hibernate5 it provi$es more optimi=ation that works a++ the time there b0 increasin" the perormance. I it is a!tomate$ persistence then it sti++ increases the perormance. Gendor independence > Irrespective o the $ierent t0pes o $atabases that are there5 hibernateprovi$es a m!ch easier wa0 to $eve+op a cross p+atorm app+ication.11) How $oes hibernate co$e +ooks +ike?: 0ession session $ get0ession+actory"*.open0ession"*;H Transaction tx $ session.beginTransaction"*;? &y'ersistanceClass mpc $ neG &y'ersistanceClass "%0ample App%*;> session.save"mpc*;@ tx.commit"*;T session.close"*;?he /ession an$ ?ransaction are the interaces provi$e$ b0 hibernate. ?here are man0 other interaces besi$es this.11) What is a hibernate 3m+ mappin" $oc!ment an$ how $oes it +ook +ike?In or$er to make most o the thin"s work in hibernate5 !s!a++0 the inormation is provi$e$ in an 3m+ $oc!ment. ?his $oc!ment is ca++e$ as 3m+ mappin" $oc!ment. ?he $oc!ment $eines5 amon" other thin"s5 how properties o the !ser $eine$ persistence c+asses8 map to the co+!mns o the re+ative tab+es in $atabase.: ;Bxml version$%:.C%Bect5 which compares ob>ect i$entit0.3. Database identit# > 6b>ects store$ in a re+ationa+ $atabase are i$entica+ i the0 represent the samerow or5 eoin etchin"5 &atch etchin"What is hibernate session and session factory? How do you configure sessionfactory in spring configuration file?Hibernate /ession is the main r!ntime interace between a Java app+ication an$ Hibernate. /essionFactor0 a++ows app+ications to create hibernate session b0 rea$in" hibernate coni"!rations i+e hibernate.c".3m+.Con9iguration c9g $ neG Con9iguration"*.con9igure"*; 22 InitialiKe the Jibernate environment0ession+actory 9actory $ c9g.build0ession+actory"*; 22 Create the session 9actory0ession session $ 9actory.open0ession"*; 22 btain the neG session object ?he ca++ to 'oni"!ration().coni"!re() +oa$s the hibernate.c".3m+ coni"!ration i+e an$ initia+i=es the Hibernate environment. 6nce the coni"!ration is initia+i=e$5 0o! can make an0 a$$itiona+ mo$iications 0o! $esire pro"rammatica++0. However5 0o! m!st make these mo$iications prior to creatin" the /essionFactor0 instance. An instance o /essionFactor0 is t0pica++0 create$ once an$ !se$ to create a++ sessions re+ate$ to a "iven conte3t. ?he main !nction o the /ession is to oer create5 rea$ an$ $e+ete operations or instances o mappe$ entit0 c+asses. Instances ma0 e3ist in one o three statesH transientH never persistent5 not associate$ with an0 /ession persistentH associate$ with a !niect represents a sin"+e !nit9o9work or a "iven $ata store an$ is opene$ b0 a /essionFactor0 instance. Wo! m!st c+ose /essions when a++ work or a transaction is comp+ete$. ?he o++owin" i++!strates a t0pica+ Hibernate sessionH 0ession session $ null; DserIn9o user $ null; Transaction tx $ null;try - session $ 9actory.open0ession"*; tx $ session.beginTransaction"*; user $ "DserIn9o*session.load"DserIn9o.class7 id*; tx.commit"*;3 catch"Exception e* - i9 "tx A$ null* -try - tx.rollback"*;3 catch "JibernateException e:* - throG neG ,AException"e:.to0tring"**; 3 3 throG neG ,AException"e.to0tring"**;3 9inally - i9 "session A$ null* -try - session.close"*;3 catch "JibernateException e* - 3 33What is the difference between hibernate get and load methods??he o++owin" Hibernate co$e snippet retrieves a 7ser ob>ect rom the $atabaseH Dser user $ "Dser* session.get"Dser.class7 userI,*; ?he "et() metho$ is specia+ beca!se the i$entiier !niect5 avoi$in" a $atabase hit i the ob>ect is a+rea$0 cache$. ?he "et() metho$ ret!rns n!++ i the ob>ect can8t be o!n$.Hibernate a+so provi$es a +oa$() metho$HDser user $ "Dser* session.load"Dser.class7 userI,*; I +oa$() can8t in$ the ob>ect in the cache or $atabase5 an e3ception is thrown. ?he +oa$() metho$ never ret!rns n!++.?he +oa$() metho$ ma0 ret!rn a pro30 instea$ o a rea+ persistent instance. A pro30 is a p+aceho+$er instance o a r!ntime9"enerate$ s!bc+ass (thro!"h c"+ib or Javassist) o a mappe$ persistent c+ass5 it can initia+i=e itse+ i an0 metho$ is ca++e$ that is not the mappe$ $atabase i$entiier "etter9metho$. 6n the other han$5 "et() never ret!rns a pro30. 'hoosin" between "et() an$ +oa$() is eas0H I 0o!8re certain the persistent ob>ect e3ists5 an$ none3istence wo!+$ be consi$ere$ e3ceptiona+5 +oa$() is a "oo$ option. I 0o! aren8t certain there is a persistent instance with the "iven i$entiier5 !se "et() an$ test the ret!rn va+!e to see i it8s n!++. 7sin" +oa$() has a !rther imp+icationH ?he app+ication ma0 retrieve a va+i$ reerence (a pro30) to a persistent instance witho!t hittin" the $atabase toretrieve its persistent state. /o +oa$() mi"ht not throw an e3ception when it $oesn8t in$ the persistent ob>ect in the cache or $atabaseS the e3ception wo!+$ be thrown +ater5 when the pro30 is accesse$.What type of transaction management is supported in hibernate? Hibernate comm!nicates with the $atabase via a J%&' 'onnectionS hence it m!st s!pport both mana"e$an$ non9mana"e$ transactions.non9mana"e$ in web containersH;bean id$%transaction&anager% class$%org.spring9rameGork.orm.hibernate.JibernateTransaction&anager%ects. ?he !nctionwith the secon$9+eve+ cache. Hibernate s!pports the o++owin" open9so!rce cache imp+ementations o!t9o9the9bo3H o 2H'ache is a ast5 +i"htwei"ht5 an$ eas09to9!se in9process cache. It s!pports rea$9on+0 an$ rea$Pwrite cachin"5 an$ memor09 an$ $isk9base$ cachin". However5 it $oes not s!pport c+!sterin".o 6/'ache is another open9so!rce cachin" so+!tion. It is part o a +ar"er packa"e5 which a+so provi$es cachin" !nctiona+ities or J/P pa"es or arbitrar0 ob>ects. It is a power!+ an$ +e3ib+e packa"e5 which5 +ike 2H'ache5 s!pports rea$9on+0 an$ rea$Pwrite cachin"5 an$ memor09 an$ $isk9base$ cachin". It a+so provi$es basic s!pport or c+!sterin" via either Java:ro!ps or JB/.o /warm'ache is a simp+e c+!ster9base$ cachin" so+!tion base$ on Java:ro!ps. It s!pports rea$9on+0 or nonstrict rea$Pwrite cachin" (the ne3t section e3p+ains this term). ?his t0pe o cache is appropriate or app+ications that t0pica++0 have man0 more rea$ operations than write operations.o J&oss ?ree'ache is a power!+ rep+icate$ (s0nchrono!s or as0nchrono!s) an$ transactiona+ cache. 7se this so+!tion i 0o! rea++0 nee$ a tr!e transaction9capab+e cachin" architect!re.o 'ommercia+ ?an"oso+ 'oherence cache.What are the different caching strategies? Aea$9on+0H ?his strate"0 is !se!+ or $ata that is rea$ reava comparator5 whi+e or$er co++ection is or$ere$ at the $atabase +eve+ !sin" or$er b0 c+a!se.What are the types of inheritence models and describe how they work like vertical inheritence andhorizontal??here are three t0pes o inheritance mappin" in hibernate H23amp+eH 4et !s take the simp+e e3amp+e o 3 >ava c+asses. '+ass Bana"er an$ Worker are inherite$ rom2mp+o0ee Abstract c+ass.1. ?ab+e per concrete c+ass with !nions H In this case there wi++ be 2 tab+es. ?ab+esH Bana"er5 WorkerIa++ common attrib!tes wi++ be $!p+icate$J2. ?ab+e per c+ass hierarch0H /in"+e ?ab+e can be mappe$ to a c+ass hierarch0. ?here wi++ be on+0 one tab+e in $atabase ca++e$ X2mp+o0eeX that wi++ represent a++ the attrib!tes reect b0 +oa$in" the reect rom the $atabase. &!t i there was not s!ch ob>ect in the $atabase then the metho$ session.+oa$(..) throws an e3ception whereas session."et(V) ret!rns n!++. What is the difference between the session.update() method and the session.lock() method? &oth o these metho$s an$ save6r7p$ate() metho$ are inten$e$ or reattachin" a $etache$ ob>ect. ?he session.+ock() metho$ simp+0 reattaches the ob>ect to the session witho!t checkin" or !p$atin" the $atabase on the ass!mption that the $atabase in s0nc with the $etache$ ob>ect. It is the best practice to !se either session.!p$ate(..) or session.save6r7p$ate(). 7se session.+ock() on+0 i 0o! are abso+!te+0 s!re that the $etache$ ob>ect is in s0nc with 0o!r $etache$ ob>ect or i it $oes not matter beca!se 0o! wi++ be overwritin" a++ the co+!mns that wo!+$ have chan"e$ +ater on within the same transaction. )oteH When 0o! reattach $etache$ ob>ects 0o! nee$ to make s!re that the $epen$ent ob>ects are reatche$ as we++. How would you reatach detached obects to a session when the same obect has already been loaded into the session? Wo! can !se the session.mer"e() metho$ ca++. What are the general considerations or best practices for defining your Hibernate persistent classes? 1. Wo! m!st have a $ea!+t no9ar"!ment constr!ctor or 0o!r persistent c+asses an$ there sho!+$ be "etCCC() (i.e accessorP"etter) an$ setCCC( i.e. m!tatorPsetter) metho$s or a++ 0o!r persistab+e instance variab+es. 2. Wo! sho!+$ imp+ement the eect. 3. It is recommen$e$ to imp+ement the /eria+i=ab+e interace. ?his is potentia++0 !se!+ i 0o! want to mi"rate aro!n$ a m!+ti9processor c+!ster. #. ?he persistent c+ass sho!+$ not be ina+ beca!se i it is ina+ then +a=0 +oa$in" cannot be !se$ b0 creatin" pro30 ob>ects. (. 7se C%oc+et ta"s or "eneratin" 0o!r \.hbm.3m+ i+es or Annotations (J%F 1.( onwar$s)5 which are +ess verbose than \.hbm.3m+ i+es. 1. What is Hibernate?Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows ou to map plain old Java objects to relational database tables using (!M") configuration files# $ts purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks#Hibernate simplifies% &aving and retrieving our domain objects Making database column and table name changes 'entrali(ing pre save and post retrieve logic 'omple) joins for retrieving related items &chema creation from object model#2. Benefits of hibernate over JDBC? Hibernate is database independent while in case of J*+', developer has to write database specific -ueries# $n case of Hibernate developer doesn.t need to be an e)pert of writing comple) -ueries as H/" simplifies -uer writing process while in case of J*+', its job of developer to write and tune -ueries# $n Hibernate, 'riteria /uer takes care of /uer 0uning# $n case of J*+' ou need to tune our -ueries# 1o need to create an connection pool in case of Hibernate# 2ou can use c3p4# $n case of J*+' ou need to write our own connection pool# 5utomatic primar ke generation# 6erformance benefits like "a( initiali(ation, Outer join fetching, +atch fetching3. Difference between different saving methods in Hibernate?saveOrUdate! +ased on some checks it will calls either save or update# 7#g# if no identifier e)ists, save is called# Otherwise update is called#save $t will 6ersists an entit and will assign an identifier if one doesn.t e)ist# $f one does, it.s essentiall doing an update# 5nd returns the generated $* of the entit#"date%$t will persist the entit using an e)isting identifier# $f no identifier e)ists, $ believe an e)ception is thrown#merge Hibernate has following three Object states#ransient$ Detached and %ersistant.Object states, with save 8 update, ou are dealing with persistant objects# 0he are linked to a &ession so Hibernate knows what has changed# +ut when ou have a transient object, there is no session involved# $n these cases ou need to use merge for updates and persist for saviing#ersist! 5s mentioned above, this is used on transient objects# $t does not return the generated $*#9#What are the Core interfaces of Hibernate framewor&?0he five core interfaces are used in just about ever Hibernate application# :sing these interfaces, ou an store and retrieve persistent objects and control transactions# &ession interface &ession;actor interface 0ransaction interface /uer and 'riteria interfacesfrom &tudent where student1ame A Esuresh. >)B14. What is %OJO?%OJO56lain Old Java Object)is a javabean that have defined setter and getter methods for all properties# *ecoupling the application code from the infrastructure frameworks isone of the man benefits of using 6OJOs# 0he also simplif development because rather than being forced to think about everthing = business logic, persistence, transactions, etc#16#What the fo"r O78 +eve+s are in hibernate?;ollowing are the four ORM levels in hibernate%a# 6ure Relationalb# "ight Object Mappingc# Medium Object Mappingd# ;ull Object Mapping1*. How to reattach detached ob(ects in hibernate? *etached objects can be reattached b calling session#merge() method of session class#1-#Difference between +oad59 and get59 method in hibernate? $f ou are sure that the object e)ists then use load() else use get() methods# load() method will throw an e)ception if the uni-ue id is not found in the database but get() method will return null if the uni-ue id is not found in the database#1.. Difference between detached state and transient state Ob(ects?0ransient objects do not have association with the databases and session objects but detached objects have corresponding entries in the database# 0hese are persistent and not connected to the &ession object# 0hese objects have the snchroni(ed data with the database when the session was closed#Fersion propert is used in hibernate to know whether an object is in transient state or in detached state#1/. Difference between the session."date59 method and the session.+oc&59 method?0he session#lock() method simpl reattaches the object to the session without checking or updating the database on the assumption that the database in snc with the detached object#:se session#lock() onl if ou are absolutel sure that the detached object is in snc with our detached object otherwise usesession."date59.C4# Different fetching strateg' in Hibernate? Join fetching%:sing an O:07R JO$1 hibernate retrieves the associated instance or collection in the same &7"7'0# Select fetching% a second &7"7'0 is used to retrieve the associated entit or collection# :nless ou e)plicitl disable la( fetching b specifing la(A?false?, this second select will onl be e)ecuted when ou access the association# Subselect fetching% a second &7"7'0 is used to retrieve the associated collections for all entities retrieved in a previous -uer or fetch# :nless ou e)plicitl disable la( fetching b specifingla(A?false?, this second select will onl be e)ecuted when ou access the association# Batch fetching! $t is an optimi(ation strateg for select fetching#:sing primar or foreign kes hibernate retrieves a batch of entit instances or collections in a single &7"7'0# ;ind the more info about ;etching strategies here# 7hcache = Hibernate &econd "evel 'ache with &pring 7)ample GH@4I@C4G3 b admin 5nother must know concept in Hibernate#Here we are going to see about Hibernate &econd "evel 'ache#Wh' we need caching? $t is mainl about application performance optimi(ation and it will happen between our application and the database to avoid the number of database hits as man as possible to give a better performance for critical applications#:sing ;ollowing 7)ample we will see how to reduce database hits#Je know Hibernate handles 1irst:+eve+ cache b default and it is associates with the )ession ob(ect# What is )econd 3eve+ Cache and How it wor&s? 0his cache is associated with )ession 1actor' Ob(ect so itdon.t bounds to single user#Jhile running the transactions, in between it loads the objects at the )ession 1actor' +evel, so that those objects will available to the entire application# &ince the objects are alread loaded in the cache, whenever an object is returned b the -uer, at that time no need to go for a database transaction# "et.s see simple e)ample program about ;etching all :sers with the help of Hibernate )econd 3eve+ Cache5;hCache9 "sing )ring.< have "sed Hibernate 4 and )ring 1ramewor& 3.2 version. $ have created following class files# 1. User8anager.(ava 2.;+ements?>TC:U@H:::XX(; !Id !GeneratedValue"strategy $ GenerationType.I,E.TIT)* 22 Generator user/se8 !Column"name $ %user/id%* private int userId; !Column"name $ %username%7 nullable $ 9alse* private 0tring username; !Column"name $ %passGord%7 nullable $ 9alse* 22 !Type"type$%encrypted0tring%* private 0tring passGord; !Column"name $ %9irstname%7 nullable $ 9alse* private 0tring 9irst.ame; !Column"name $ %lastname%7 nullable $ 9alse* private 0tring last.ame; !Column"name $ %email%7 nullable $ 9alse* private 0tring email; !Column"name $ %role%7 nullable $ 9alse*$'$($)$*%!%"%#%$%% private 0tring role $ %D0E6%; 22 Generate getters and setters 9or above 9ields. parent reatonshp woud be created.In Hbernate, ony the "reatonshp owner" shoud mantan the reatonshp, and the "nverse" keyword s created to denes whch sde s the owner to mantan the reatonshp. However the "nverse" keyword tsef s not verbose enough, I woud suggest change the keyword to "reatonshp_owner".In short, nverse="true" means ths s the reatonshp owner, and nverse="fase" (defaut) means ts not.Suppose Stock s parent and StockDayRecords s Chd ob|ect.Inverse keyword s apped n one to many reatonshp. Heres the queston, f save or update operaton perform n "Stock" ob|ect, shoud t update the "stockDayRecords" reatonshp?1. nverse="true"If nverse="true" n the set varabe, t means "stock_day_record" s the reatonshp owner,so Stock w NOT UPDATE the reatonshp.2. nverse="fase"If nverse="fase" (defaut) n the set varabe, t means "stock" s the reatonshp owner, and Stock w UPDATE the reatonshp.If keyword "nverse" s not dene, the nverse = "fase" w be used, whch sHow do you nvoke Stored Procedures?Ans. { ? = ca seectAEmpoyees() }

Expan Crtera API?Ans. Crtera s a smped API for retrevng enttes by composng Crteron ob|ects. Ths s a very convenent approach for functonaty ke "search" screens where there s a varabe number of condtons to be paced upon the resut set. Exampe : Lst empoyees = sesson.createCrtera(Empoyee.cass) .add(Restrctons.ke("name", "a%") ) .add(Restrctons.ke("address", "Boston")) .addOrder(Order.asc("name") ) .st();s 34. What are the benets does HbernateTempate provde?Ans. The benets of HbernateTempate are : * HbernateTempate, a Sprng Tempate cass smpes nteractons wth Hbernate Sesson. * Common functons are smped to snge method cas. * Sessons are automatcay cosed. * Exceptons are automatcay caught and converted to runtme exceptons. How w you congure Hbernate?Ans. The conguraton es hbernate.cfg.xm (or hbernate.propertes) and mappng es *.hbm.xm are used by the Conguraton cass to create (.e. congure and bootstrap hbernate) the SessonFactory, whch n turn creates the Sesson nstances. Sesson nstancesare the prmary nterface for the persstence servce. " hbernate.cfg.xm (aternatvey can use hbernate.propertes): These two es are used to congure the hbernate sevce (connecton drver cass, connecton URL, connecton username, connecton password, daect etc). If both es are present n the casspath then hbernate.cfg.xm e overrdes the settngs found n the hbernate.propertes e. " Mappng es (*.hbm.xm): These es are used to map persstent ob|ects to a reatona database. It s the best practce to store each ob|ect n an ndvdua mappng e (.e mappng e per cass) because storng arge number of persstent casses nto one mappng e can be dmcut to manage and mantan. The namng conventon s to use the same name as the persstent (PO|O) cass name. For exampe Account.cass w have a mappng e named Account.hbm.xm. Aternatvey hbernate annotatons can be used as part of your persstent cass code nstead of the *.hbm.xm es.What s a SessonFactory? Is t a thread-safe ob|ect?Ans. SessonFactory s Hbernates concept of a snge datastore and s threadsafe so that many threads can access t concurrenty and request for sessons and mmutabe cache of comped mappngs for a snge database. A SessonFactory s usuay ony but once at startup. SessonFactory shoud be wrapped n some knd of sngeton so that t can be easy accessed n an appcaton code.What s a Sesson? Can you share a sesson ob|ect between dherent threads?Ans. Sesson s a ght weght and a non-threadsafe ob|ect (No, you cannot share t between threads) that represents a snge unt-of-work wth the database. Sessons are opened by a SessonFactory and then are cosed when a work s compete. Sesson s the prmary nterface for the persstence servce. A sesson obtans a database connecton azy (.e. onywhen requred). To avod creatng too many sessons ThreadLoca cass can be used as shown beow to get the current sesson no matter how many tmes you make ca to the currentSesson() method.What are the pros and cons of detached ob|ects?Ans. Pros: " When ong transactons are requred due to user thnk-tme, t s the best practce to break the ong transacton up nto two or more transactons. You can use detached ob|ects from the rst transacton to carry data a the way up to the presentaton ayer. These detached ob|ects get moded outsde a transacton and ater on re-attached to a new transacton va another sesson. Cons " In genera, workng wth detached ob|ects s qute cumbersome, and better to not cutter up the sesson wth them f possbe. It s better to dscard them and re-fetch them on subsequent requests. Ths approach s not ony more portabe but aso more emcent because - the ob|ects hang around n Hbernate's cache anyway. " Aso from pure rch doman drven desgn perspectve t s recommended to use DTOs (DataTransferOb|ects) and DOs (DomanOb|ects) to mantan the separaton between Servceand UI ters.What s the dherence between the sesson.update() method and the sesson.ock() method?Ans. Both of these methods and saveOrUpdate() method are ntended for reattachng a detached ob|ect. The sesson.ock() method smpy reattaches the ob|ect to the sesson wthout checkng or updatng the database on the assumpton that the database n sync wththe detached ob|ect. It s the best practce to use ether sesson.update(..) or sesson.saveOrUpdate(). Use sesson.ock() ony f you are absoutey sure that the detached ob|ect s n sync wth your detached ob|ect or f t does not matter because you w be overwrtng a the coumns that woud have changed ater on wthn the same transacton. Note: When you reattach detached ob|ects you need to make sure that the dependent ob|ects are reatched as we.How woud you reatach detached ob|ects to a sesson when the same ob|ect has areadybeen oaded nto the sesson?Ans. You can use the sesson.merge() method ca.What are the genera consderatons or best practces for denng your Hbernate persstent casses?Ans. 1.You must have a defaut no-argument constructor for your persstent casses and there shoud be getXXX() (.e accessor/getter) and setXXX( .e. mutator/setter) methods for a your persstabe nstance varabes. 2.You shoud mpement the equas() and hashCode() methods based on your busness key and t s mportant not to use the d ed n your equas() and hashCode() denton f the d ed s a surrogate key (.e. Hbernate managed denter). Ths s because the Hbernate ony generates and sets the ed when savng the ob|ect. 3. It s recommended to mpement the Serazabe nterface. Ths s potentay usefu f you want to mgrate around a mut-processor custer. 4.The persstent cass shoud not be na because f t s na then azy oadng cannot be used by creatng proxy ob|ects. 5.Use XDocet tags for generatng your *.hbm.xm es or Annotatons (|DK 1.5 onwards), whch are ess verbose than *.hbm.xm es.What s CRUD?Ans. A CRUD operaton deas wth creatng , retrvng , updatng and deetng from the tabe.We have aready descrbed prevousy how to persst "Empoyee" Cass to database. Here weare addng more operaton on thatEmpoyee Cass.1. Creatng/Persstng the cass to databae2. Retrvng records from database3. Updatng decord(Condton : Where sa s 8000 ,update sa to 11000)4. Deetng decord (condton: where deptno s 30)Expan the fe cyce method of E|B?1. Ans. Lfe Cyce of Entty Bean:Frst stage s Does Not Exst Stage then Contaner creates the nstance of E|B and caSetEnttyContext() method whch w set a entty context to bean and now t w become avaabe on poo ,to get a partcuar dentty of an E|B ob|ect t has to move from Pooed stage to ready stage whch s done by cang the create () method whch n turns ca e|bCreate() and e|bPostCreate() method .There s another way by whch drecty entty bean can move to pooed stage to ready stage thats s ca e|bActvate() method.now we are ready to nvoke the busness method of entty bean .After competon of busness method f we want to move agan n pooed stage from ready stage we can ca remove() method whch n turns ca e|bRemove() or drecty ca e|bPassvate () method.At the end contaner remove the nstance of E|Bfrom poo and ca unSetEnttyContext().Lfe Cyce of Statefu Sesson Bean :Statefu sesson beans fe cyce starts when cent ca create() method.The contanercreate the nstance of sesson bean and ca setSessonContext() and e|bCreate() methodNow the statefu sesson bean s ready to serve the cent request after servng the request f t s not used after a ong tme contaner can move ths bean to passve stage by cang the e|bPassvate() method.smary when bean s n passve stage and cent nvoke the busness method the contaner ca e|bActvate() method to move bean from passve stage to actve or ready stage.At the end of fe cyce cent ca remove() method and contaner w ca e|bRemove() method and bean s ready for garbage coecton.Lfe Cyce of Stateess sesson bean :Staes sesson bean has short fe cyce t can have two stage does not exst and ready stage. e|b contaner create the nstance of stateess sesson bean and ca setSessonContext () and e|bCreate() method.Now the bean s ready to nvoke busness method on ths.t w not mantan the state so remove () method s been caed after competon of busness method whch n turns ca e|bRemove () and now ts ready for garbage coecton.Lfe cyce of Message Drven bean:MDBs have same fe cyce ke stateess sesson bean. setMessageDrvenContext() method and e|bCreate() method s caed by contaner to create the nstance of MDB.now ts ready to receve message .and at the end of fecyce cent w ca remove () methodwhch n turns ca e|bRemove () and now ts ready for garbage coecton.Difference between session/save)* , session/saveOrUpdate)* and session/persist)*? session/save)* < ave does an insert and will fail if the primar# (e# is alread# persistent/ session/saveOrUpdate)* < saveOrUpdate does a select first to determine if it needs to do an insert or an update/ Insert data if primar# (e# not e@ist otherwise update data/ session/persist)* < Does the same li(e session/save)*/ ,ut session/save)* return erialiCable ob'ect but session/persist)* return void/ session/save)* returns the generated identifier )erialiCable ob'ect* and session/persist)* doesnIt/ $or -@ample < if #ou do