Hibernate - Basic

817 views

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
817
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • 30 to 70% of developer time, maintenance
  • Granularity – Objects and tables are modeled at different level of granularity Table structure is often de-normalized for better performance Objects are more fined grained
  • Inheritance – Associations in java uni or bi, type of object impact association DB – no directionality, many to many relationship needs join table, id or FK impacts association Navigational differences
  • Lazy loading – OptionVolatility example
  • Hibernate - Basic

    1. 1. > Hiber t -Ba nae sic Present on 15th Feb 20 ed 12
    2. 2. @Before> OOPs Must> L w houtHiber t ife it nae 2
    3. 3. Definit ion> Obj R aiona M pping (OR )sol ion forJ V ect el t l a M ut AA> Itis apow ful high per ma obj /el t lper ence a quer ser ice er , for nce ectr aiona sist nd y v> M ps J V cl sses t daa se t bl a A A a o t ba a es> In E ish, pr ides t t getJ v obj s in a outofdaa se ngl ov ool o a a ect nd t ba 3
    4. 4. Obj M v R aiona M ect odel s el t l odel Relational Databases • Efficient data storage, retrieval and integrity of the data • Provide a “normalized” set of data 4
    5. 5. Obj - el t lmismach ectR aiona t> Ga ait r nul r y – Obj Or ed v Daa se T ect ient s. t ba ypes – UserDefined Col T (UDT ae notpora e - umn ypes ) r t bl Name UserID Password PAN City S tate Zip User Address LoginInfo Name City PAN Username State Password Zip 5
    6. 6. Obj - el t lmismach ectR aiona t> Inher a &Pol phism it nce ymor – Notsuppored in t r aiona model t he el t l – No pol phic quer ymor ies – Col ae stictyt umns r r l yped> Ident yM t it ismach – Obj Ident yv Obj E l y ect it s. ect quait – Differ obj s ca ma t t sa col orcol ent ect n p o he me umn umns – Daa se Ident yStaegies t ba it r t – Naur lKeys v sus Surogae Keys ta er r t 6
    7. 7. Obj - el t lmismach ectR aiona t> A t ssociaions – Obj R ences v sus F eign Keys ect efer er or – Dir ionait ofA t ect l y ssociaions – T bl a t ae aw ys one-o- nyorma t one a es ssociaions r l a t ma ny-o- – Obj a t ca be ma t ma ect ssociaions n ny-o- ny> Daat mismach t ype t 7
    8. 8. Obj - el t lma ectR aiona pping> T s/echniques t st e a r r e obj s fr adaa se ool t o or nd etiev ect om t ba> F om t code per iv itbeha es l av t lobj daa se r he spect e v ike irua ect t ba> Acompl e OR sol ion shoul pr ide: et M ut d ov – Ba CR funct l y sic UD ionait – A Obj - ient Quer F cil y n ectOr ed y a it – M ppingM a t suppor a et daa t – Ta ct lCa bil y r nsa iona pa it 8
    9. 9. W tHiber t offer ha nae s?> Decl r t e pr a aaiv ogr mming> Uses R ime R ect unt efl ion> Quer L ngua is SQLl y a ge -ike – Lev a pr a ’s knowedge er ges ogr mmer l> M ppings a – Defined a XM document ora a aions s L s s nnot t 9
    10. 10. Concept s> Configur t (cfg) aion> Session F ct y– cfg.buil a or dSessionF ct y() a or – is aca ofcompil ma che ed ppings forasingl daa se. e t ba – Is used t cr t Hiber t Sessions o eae nae> Session – sf.openSession() – Shor l ed t iv • T aybr bet een t a a t daast a empor r idge w he pp nd he t or ge – Pr ides CR oper t on Obj s ov UD aions ect – Wa aJ Connect /J EDaaSour r ps DBC ion 2E t ce – Ser es a afir l elobj ca v s st ev ect che 10
    11. 11. Concept s> Ta ct – session.beginTa ct r nsa ion r nsa ion() – itpr ides a r ct fr t underying impl aion (J JA ov bsta ion om he l ement t DBC, T ) – itis opt l iona 11
    12. 12. Lifecycl e> Ta r nsient – NotA t w h adaa se t bl ssociaed it t ba a e – Non-r nsa iona ta ct l> Per ed sist – Obj w h Daa se Ident y ect it t ba it – A t obj w aSession ssociaes ect ith – Ta ct l r nsa iona> Det ched a – no l ongerguaa eed t be in synch w h t daa se r nt o it he t ba 12
    13. 13. Achit ur r ect e Ima sour O’R IL Y ge ce E L 13
    14. 14. O/ M ppings R a> Hiber t M ppingdefine: nae a – Col t F d M ppings umn o iel a – Pr r Keyma &gener t Scheme imay pping aion – A t ssociaions – Colect l ions – Ca Setings ching t – Cust SQL om – A ma mor setings… nd ny e t 14
    15. 15. HBMma fil pping e> < hiber t ma nae- pping> pa ge= "com.t v nt in"> cka a a .doma> < cl ss na “St "> a me= udent> < id na "Id" col “ST NT t “l me= umn= UDE _ID" ype= ong">> < gener t cl ss= "ident y" / aor a it >> </ id>> < pr t na “ST NT M “ / opery me= UDE _NA E >> < set na "cour t bl "ST NT me= ses" a e= UDE _COUR " ca de= "al SE sca l">> < key col "ST NT / umn= UDE _ID" >> < ma t ma col "COUR _ID" ny-o- ny umn= SE> cl ss= “com.t v nt in.Cour / < / a a a .doma se" > set> < /a cl ss>> < / nae- pping> hiber t ma 15
    16. 16. A aion ba ma nnot t sed pping> @Entity> @Table( name = " students" )> publ cl ss St { ic a udent @Id> @GeneratedValue> @Column( name = " student_id" )> pr ae l st Id; iv t ong udent> @Column( name = " student_name" , nullable = false, length = 100)> pr ae St ingst Na iv t r udent me;> @ManyToMany( cascade = CascadeType.ALL)> @JoinTable( name = " student_course" , joinColumns = {@JoinColumn( name = " student_id" ) }, inverseJoinColumns = {@JoinColumn( name = " course_id" ) })> pr ae Set Cour cour = newHa < Cour (0 iv t < se> ses shSet se> ); 16
    17. 17. Sa inga Obj v n ect> St st = newSt (); udent udent udent > POJ is cr t O eaed> ….. > St r aSession at> Session session = nul; l > Ta ct is st red r nsa ion at> Ta ct t = nul; r nsa ion x l > T obj is sa ed he ect v> ty{ r > T ta ct is commited he r nsa ion t> session = fa or ct y.openSession();> t = session.beginTa ct x r nsa ion(); > T session is cl he osed> session.sa e(st ); v udent> t x.commit ();> } final { ly> session.cl ose();> } 17
    18. 18. L dinga Obj oa n ect> St st = nul; udent udent l > St r aSession at> Session session = nul; l > POJ is l ded O oa> session = fa or ct y.openSession(); > PKa Obj Cl ss ae pr ided nd ect a r ov> ty{ r > T session is cl he osed> st = (St ) udent udent> session.get udent a id); (St .cl ss,> } final { ly> session.cl ose();> } 18
    19. 19. Del inga Obj et n ect> Session session = nul; l > St r aSession at> Ta ct t = nul; r nsa ion x l > Ta ct is st red r nsa ion at> ty{ r > T obj is del ed he ect et> session = fa or ct y.openSession(); > T ta ct is commited he r nsa ion t> t = session.beginTa ct x r nsa ion(); > T session is cl he osed> session.del e(st ); et udent> t x.commit ();> …> } final { ly> session.cl ose();> } 19
    20. 20. W kingw h Colect or it l ions> Ca r esentaparent-child/one-many r aionship usingmostoft a a a e n epr el t he v il bl J v Colect a a l ions> Per ence byr ch- bil y sist ea a it> No a sema ics t yourcolect dded nt o l ions> Aa a e Colect ma v il bl l ion ppings he t ba ppings ae defined byaforeign key t t ow paentent y> In t daa se ma r o he ning/ r it 20
    21. 21. Suppored A t t ssociaions> One-o- t one – M int ined w h For Keys in Daa se a a it eign t ba> One-o- ny/M ny-o- t ma a t one – Obj on t ‘one’ side ect he – Colect on t ma ‘side’ l ion he ny> M ny-o- a a t M ny – Use a‘mapping’ t bl in t daa se a e he t ba 21
    22. 22. A t At ibut ssociaions tr es> Inv se atibut used forbi- ect la t er tr e dir iona ssociaions> L zyL ding a oa – Configur perr aionship ed el t – Uses dyna pr a R ime mic oxies t unt> Ca dingSt es sca yl – “none” no oper t ae ca ded aions r sca – “al aloper t ae ca ded l” l aions r sca – E er oper t in Hiber t ha acorespondingca de st e v y aion nae s r sca yl 22
    23. 23. Hiber t Quer L ngua (HQL nae y a ge )> A obj ified v sion ofSQL n ect er – Pol phic Quer ymor ies – Obj paa er in Quer ect r met s ies – Less v bose t n SQL er ha> Doesn’thide t pow ofSQL he er – SQLj Cat n pr s oins, resia oduct – Pr ect oj ions – A egaion (ma a g)a gr ggr t x, v nd ouping – Or ing der – Sub- ies quer 23
    24. 24. Hiber t Quer L ngua (HQL nae y a ge )> Simpl HQLQuer est y – R ur alSt s et n l udent s e s s i o n = s e s s i o n F a c t o r y .openSession(); // query string – ‘Student’ refers to a Class not a Table String q u e r y S t r i n g = " f r o m S t u d e n t " ; // create, configure and execute the query List students = s e s s i o n .c r e a t e Q u e r y (q u e r y S t r i n g ).l i s t (); 24
    25. 25. Hiber t Quer L ngua (HQL nae y a ge )> Amor el bor t HQLQuer e a ae y – R ur alst s w h st ids et n l udent it udent Student s t u d e n t = … s e s s i o n = s e s s i o n F a c t o r y .openSession(); // build a query string String q u e r y S t r i n g = “f r o m S t u d e n t a s s wh e r e s .s t u d e n t I d = :id ”; // create, configure and execute the query List students = s e s s i o n .createQuery(q u e r y S t r i n g ) .setObject(“id”, 12 2 2 2 ) .list(); 25
    26. 26. Hiber t Quer L ngua (HQL nae y a ge )> Amor el bor t HQLQuer e a ae y – R ur alst s w h st ids et n l udent it udent Student s t u d e n t = … s e s s i o n = s e s s i o n F a c t o r y .openSession(); // build a query string String q u e r y S t r i n g = “f r o m S t u d e n t a s s wh e r e s .s t u d e n t I d in = :id l is t ”; // create, configure and execute the query List students = s e s s i o n .createQuery(q u e r y S t r i n g ) .setParameterList(“id l is t ”, <<l i s t o f i d >>) .list(); 26
    27. 27. Quer byCr er y it ia> Sa quer usingt Cr er A me y he it ia PI – R ur alst s w h st ids et n l udent it udent Student s t u d e n t = … s e s s i o n = s e s s i o n F a c t o r y .openSession(); // create and expression to match the given conference Expression e x p = Expression.eq(“studentId", 12 3 4 5 ); List addresses = session .createCriteria(S t u d e n t .class) .add(e x p ) .list(); 27
    28. 28. Quer byE mpl y xa e> R ur alst w h st id et n l udent it udentStudent student = new Student();student.setStudentId(12345);// create example objectExample e x a m p l e = Example.create(s t u d e n t ) .ignoreCase() .enableLike(MatchMode.ANYWHERE);// create, configure and execute the queryList matches = s e s s i o n .createCriteria(S t u d e n t .class) .add(e x a m p l e ).list(); 28
    29. 29. Inher a it nce> Suppor St aegies t rt – Singl t bl percl ss hier r eae a achy – J subcl sses oined a – Inher pr t fr super a it operies om cl sses 29
    30. 30. Singl t bl percl ss eae a> @E it nt y> @Inher a r t Inher a ype.SING E A E it nce(st aegy= it nceT L _T BL )> @Discr t Col iminaor umn(> na "pl net me= a ype",> discr t T Discr t T iminaor ype= iminaor ype.STRING> )> @Discr t V l iminaor aue("Pl ne") a> publ cl ss Pl ne { ... } ic a a> @E it nt y> @Discr t V l 3 ") iminaor aue("A 20> publ cl ss A 20ext Pl ne { ... } ic a 3 ends a 30
    31. 31. J subcl ssesoined a> @E it nt y> @Inher a r t Inher a ype.J D) it nce(st aegy= it nceT OINE> publ cl ss Boa impl s Ser l bl { ... } ic a t ement iaiza e> @E it nt y> publ cl ss F r ext Boa { ... } ic a ery ends t> @E it nt y> @Pr r oinCol imayKeyJ umn(na "BOA_ID") me= T> publ cl ss A ica a ext Boa { ... } ic a mer CupCl ss ends t 31
    32. 32. Inher fr super a it om cl sses> @M ppedSuper a a cl ss> publ cl ss Ba nt y{ ic a seE it> @Basic> @Tempor l empor l ype.T E A P) a(T aT IM ST M> publ Dae get a Updae(){ ... } ic t L st t> publ St ingget a Updaer { ... } ic r L st t ()> ...> }> @E it cl ss Or ext Ba nt y{ nt y a der ends seE it> @Id publ Int get { ... } ic eger Id()> ...> } 32
    33. 33. Ca in Hiber t ching nae> 1stL el ev – Ta ct scoped ca pr ided byt Session. r nsa ion che ov he – Aw ys a a a e l a v il bl> 2nd L el ev – Pr scoped ca ocess che – Shaed byalSessions r l – Opt l iona – Pl bl impl aion, ca be cl er ugga e ement t n ust ed> Query – Use w h cae, pr e fir it r ofil st 33
    34. 34. Ca in Hiber t ching nae> @T bl me = "st s") a e(na udent @Ca bl chea e @Cache(usa = ge CacheConcurencyStaegy.R A R E r r t E D_W IT ) publ cl ss St { ic a udent 34
    35. 35. Lifecycl e 35
    36. 36. W t use? hy o> G sepaaion ofint aion t a t r oft a icaion ood r t egr t ier nd he est he ppl t> Independentofunderyingdaa se used l t ba> EfficientQuer forPer ma ies for nce – La Loa zy ding> L yer Design Pat n a ed ter> Aoid r ent t w v einv ing he heel> G communit suppor, l r pooloft l ood y t age aent 36
    37. 37. > T nk Y ha ou

    ×