SlideShare a Scribd company logo
> Hiber t -Ba
       nae sic

 Present on 15th Feb 20
       ed              12
@Before
> OOPs Must
> L w houtHiber t
   ife it      nae




                     2
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
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
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
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
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
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
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
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
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
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
Achit ur
 r ect e




           Ima sour O’R IL Y
              ge ce E L




                               13
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Quer byE mpl
    y xa e
> R ur alst w h st id
   et n l udent it udent
Student student = new Student();
student.setStudentId(12345);


// create example object
Example 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 query
List 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
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
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
J subcl sses
oined 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
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
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
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
Lifecycl
       e




           35
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
> T nk Y
   ha ou

More Related Content

PDF
手把手教你 R 語言分析實務
PDF
02 probabilistic inference in graphical models
DOCX
WALI-ALLAH
XLSX
Uspto reexamination request - update - april 12 to april 18, 2011 - invn tree
PDF
Caldwell recognition-2012
XLS
fdhgfh
PDF
2016 10 mathematics_sample_paper_sa2_03_ans_z657f
PDF
KMIT 1 ASSOCIATE
手把手教你 R 語言分析實務
02 probabilistic inference in graphical models
WALI-ALLAH
Uspto reexamination request - update - april 12 to april 18, 2011 - invn tree
Caldwell recognition-2012
fdhgfh
2016 10 mathematics_sample_paper_sa2_03_ans_z657f
KMIT 1 ASSOCIATE

Viewers also liked (16)

PDF
Non Sales Sales Letter
PPTX
How to Market GoodDining
PDF
May 2012 Devil's Corner 1HBCT Newsletter
ODP
12 laj16
PDF
Combine august 2013 for web
PDF
Li Fang Digital Introduction
DOCX
Resume
PDF
V0310 nopalea-helps-this-fitness-expert-keep-moving
PDF
F1 2011 Korea Race Report
PDF
刘苏雨-AHU-SCM
DOCX
Pembagian iklim
PDF
8 part 1-dozakh say bachney ka aasan tariqa
PDF
[Webinar] How to integrate MS Dynamics NAV with Salesforce
PDF
Tableau récapitulatif des formes de salutation
TXT
Instrucciones
PDF
Spring promo v18[1]
Non Sales Sales Letter
How to Market GoodDining
May 2012 Devil's Corner 1HBCT Newsletter
12 laj16
Combine august 2013 for web
Li Fang Digital Introduction
Resume
V0310 nopalea-helps-this-fitness-expert-keep-moving
F1 2011 Korea Race Report
刘苏雨-AHU-SCM
Pembagian iklim
8 part 1-dozakh say bachney ka aasan tariqa
[Webinar] How to integrate MS Dynamics NAV with Salesforce
Tableau récapitulatif des formes de salutation
Instrucciones
Spring promo v18[1]
Ad

Similar to Hibernate - Basic (20)

PPT
01 Introduction To Dbms
PDF
Os Zaitsev
PDF
From Data to Knowledge
PPTX
NoSQL learnings from the world of Telco
PDF
cl liu.pdf
PDF
TELEPHONE BILLING SYSTEM
PDF
Transcript_HarshMehta
PPT
Mix mode GIS for Transmission Company
KEY
Graphs in the Database: Rdbms In The Social Networks Age
PDF
Microaccess 2007
PDF
Pervasive
PDF
Modeling avengers – open source technology mix for saving the world
PDF
Modeling avengers – open source technology mix for saving the world econ fr
PPT
Object Relational Mapping with LINQ To SQL
PPT
Alison Fleming Michael Upton Collaborating for Success
PPTX
Software Presentation
PDF
Lecture notes 2
PDF
Evolving systems and the link to service orientation
PDF
C.V Abdullah
01 Introduction To Dbms
Os Zaitsev
From Data to Knowledge
NoSQL learnings from the world of Telco
cl liu.pdf
TELEPHONE BILLING SYSTEM
Transcript_HarshMehta
Mix mode GIS for Transmission Company
Graphs in the Database: Rdbms In The Social Networks Age
Microaccess 2007
Pervasive
Modeling avengers – open source technology mix for saving the world
Modeling avengers – open source technology mix for saving the world econ fr
Object Relational Mapping with LINQ To SQL
Alison Fleming Michael Upton Collaborating for Success
Software Presentation
Lecture notes 2
Evolving systems and the link to service orientation
C.V Abdullah
Ad

Recently uploaded (20)

PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
Spectroscopy.pptx food analysis technology
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
cuic standard and advanced reporting.pdf
PDF
Machine learning based COVID-19 study performance prediction
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Programs and apps: productivity, graphics, security and other tools
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Spectroscopy.pptx food analysis technology
Spectral efficient network and resource selection model in 5G networks
sap open course for s4hana steps from ECC to s4
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Encapsulation_ Review paper, used for researhc scholars
Mobile App Security Testing_ A Comprehensive Guide.pdf
MIND Revenue Release Quarter 2 2025 Press Release
Review of recent advances in non-invasive hemoglobin estimation
Unlocking AI with Model Context Protocol (MCP)
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
cuic standard and advanced reporting.pdf
Machine learning based COVID-19 study performance prediction
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Diabetes mellitus diagnosis method based random forest with bat algorithm
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Programs and apps: productivity, graphics, security and other tools

Hibernate - Basic

  • 1. > Hiber t -Ba nae sic Present on 15th Feb 20 ed 12
  • 2. @Before > OOPs Must > L w houtHiber t ife it nae 2
  • 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. Achit ur r ect e Ima sour O’R IL Y ge ce E L 13
  • 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. Quer byE mpl y xa e > R ur alst w h st id et n l udent it udent Student student = new Student(); student.setStudentId(12345); // create example object Example 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 query List 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. 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. 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. J subcl sses oined 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. 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. 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. 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. Lifecycl e 35
  • 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. > T nk Y ha ou

Editor's Notes

  • #3: 30 to 70% of developer time, maintenance
  • #6: 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
  • #8: 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
  • #37: Lazy loading – OptionVolatility example