03-Hibernate-Association and Collection Mapping

download 03-Hibernate-Association and Collection Mapping

of 27

Transcript of 03-Hibernate-Association and Collection Mapping

  • 8/16/2019 03-Hibernate-Association and Collection Mapping

    1/27

    © 2009 coreservlets.com

     Collection Mapping

    Originals of Slides and Source Code for Examples:

    http://courses.coreservlets.com/Course-Materials/hibernate.html

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    © 2009 coreservlets.com

    For live Spring & Hibernate training, seecourses a p: courses.coreserv e s.com .Taught by the experts that brought you this tutorial.

    ,can be held on-site at your organization.

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    • ourses eve ope an aug y ar y a – Java 5, Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF, Ajax, GWT, custom mix of topics

    • Courses developed and taught by coreservlets.com experts (edited by Marty) – Spring, Hibernate/JPA, EJB3, Ruby/Rails

    Contact [email protected] for details

  • 8/16/2019 03-Hibernate-Association and Collection Mapping

    2/27

    Topics in This Section

    • Understand Collection and

    Association relationships•  Java and databases

    •  approach of mapping both

    o ec ons an ssoc a ons.

    4

    © 2009 coreservlets.com

    e a ons ps

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

  • 8/16/2019 03-Hibernate-Association and Collection Mapping

    3/27

    Relationship Types

    • Association

     – Mapping relationships between two objects – 

    • Account and AccountOwner 

     – Collection of values representing individual p eces o a a

     – Example• Map of holidays

    • String array of months

    Relationship Dimensions

    • Relationshi s between entities canexist in multiple ways – 

    • How many on each side of the

    relationshi ? – Directionality

    • From which side s of the relationshi can you access the other?

    •  relationships

  • 8/16/2019 03-Hibernate-Association and Collection Mapping

    4/27

    Relationship Multiplicity

    • One-to-Many –    s ng e ccoun as many ransac ons

     – Reverse of a many-to-one relationship• Man -to-One –  Multiple Transactions belong to a single account – Reverse of a one-to-many relationship

    • - - – A single AccountOwner has a single HomeAddress – A sin le HomeAddress has a sin le AccountOwner 

    • Many-to-Many

     –  Multiple Accounts have multiple AccountOwners –  en rea ze roug wo one- o-many re a ons ps

    •  A single Account has multiple AccountOwners•  A single AccountOwner has multiple Accounts

    Relationship Directionality

    • Unidirectional –  an on y traverse o ects rom one s e o t e

    relationship

     – Example: Account : Transaction• Given an Account object, can obtain related

    Transaction objects.

    • Given a Transaction object, cannot obtain related Account object.

    • Bidirectional –   

     – Example: Account : Transaction• Given an Account object, can obtain related

    .• Given a Transaction object, can obtain related Account object.

  • 8/16/2019 03-Hibernate-Association and Collection Mapping

    5/27

    © 2009 coreservlets.com

     Relationships

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    Java vs. Database

    • Java – Objects are inherently directional

    • An object has a reference/pointer to another

     – Transition by walking a networked graph of

    object references• Database

     – Relations are not inherently directional•   a e can ar rar y o n s co umns w

    columns of other tables (not just those keyedto)

     – Transition by joining tables together through joins/foreign keys

    *Source: Java Persistence with Hibernate

  • 8/16/2019 03-Hibernate-Association and Collection Mapping

    6/27

    Relationships in Java

    • Object has an attribute referencing another related

    • For ‘Many’ side, Collections API –  Set

     • Objects organized with or without order 

     –  Map•   ,• Can be organized with or without order 

     –  List• Du lication allowed• Objects expected to be organized in an order 

     –  Arrays• Duplication allowed• Objects expected to be organized in an order • Strongly typed to particular object type, and lacks ability to resize

    Relationships in Database

    • Record relationships can be realized usingseveral techniques – Denormalized table

    •   ,different relationship data.

     – Foreign keys• o ow en ers o re a e recor s on o er a es

     –  Join tables• Tables specifically setup to maintain a relationship

    between two identities (usually for M:M)

     – Ad hoc joins in a query•  

    • Each technique has its pros/cons

  • 8/16/2019 03-Hibernate-Association and Collection Mapping

    7/27

    Relationships in Database

    • Denormalized Table –  Pros

    • Very fast• Easy to query against

     –  Cons

    • Contains redundant data

    • Requires many nullable columns

    Relationships in Database

    • Foreign Keys –  Pros

    • Reduce redundancy

    • Better modeling of data

     –  Cons

    • Slower than denormalized table

    • Slightly more complicated to query against

    HEALTH_PLANEMPLOYEE

    HEALTH_PLAN_REP

    HEALTH_PLAN_NAME

    HEALTH_PLAN_ID

    EMPLOYEE_ADDRESS

    EMPLOYEE_NAME

    EMPLOYEE_ID

     _ 

    HEALTH_PLAN_ID

  • 8/16/2019 03-Hibernate-Association and Collection Mapping

    8/27

    Relationships in Database

    • Join Tables – 

    • Built on foreign key model, enables many:many relationships

     –  Cons•   ,

    CONTRACTOR_ID

    CONTRACTOR

    CUSTOMER_ID

    CUSTOMER

    CONTRACTOR_PHONE

    CONTRACTOR_NAME

    CUSTOMER_PHONE

    CUSTOMER_ADDRESS

     _ 

    CONTRACT_ID

    CONTRACTOR_ID

    CUSTOMER_ID

     _ 

    PRICE

    START_DATE

    Relationships in Database

    • Joins –  Pros

    •  Allows for any possible query a user can think of without havingto predefine the requirements in the schema design

     –  Cons• No model enforcement

     – Can join ‘age’ and ‘office floor’ columns – but does it make sense?• Can be complicated/confusing to write; results may not appear

    as desiredSELECT CONTRACTOR_NAME FROM CONTRACTOR WHERE CONTRACTOR_STATE = (SELECTCUSTOMER_STATE FROM CUSTOMER WHERE CUSTOMER_NAME='JOHN SMITH');

    CONTRACTOR NAME

    CONTRACTOR_ID

    CONTRACTOR

    CUSTOMER_NAME

    CUSTOMER_ID

    CUSTOMER

    CONTRACTOR_STATE

     _ 

    CUSTOMER_STATE

    CUSTOMER_ADDRESS

    CUSTOMER_PHONE

  • 8/16/2019 03-Hibernate-Association and Collection Mapping

    9/27

    © 2009 coreservlets.com

     with Hibernate

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    Domain ob ect ra h models• Hibernate represents domain object

    .

    A C F G

    B D   E

     model updates for objects on both sides –  Need to keep all in-memory objects up-to-date.

     –  If Objects A and B have a bidirectional relationship, andObject B is added to Object A, need to make sure thatObject A also gets added to Object B

     – Can cause complication when persisting the relationship• Which side should save the relationship?

  • 8/16/2019 03-Hibernate-Association and Collection Mapping

    10/27

    Markin the Savin Side

    “inverse” attribute – Used for both 1:M/M:1 and M:M relationships

     – For 1:M/M:1•  

    single object side of the relationship

     – For M:M• One side of the relationship• If used, must be on the non-idbag

    • “property-ref” attribute –   • Either side of the relationship, but only once

    Settin u Relationshi s1. Determine your domain model relationships

    • Define each as an association or collection

    • Identify the multiplicity between objects

     • Does it need to be bidirectional?

    2. Define your relationship implementation typesand add the Interface representation of eachassociation/collection to appropriate domain

    , , , …

    3. Create the mappings in the correspondingobject mapping files

    4. If bidirectional, optionally add bidirectionalmaintenance code

  • 8/16/2019 03-Hibernate-Association and Collection Mapping

    11/27

    Collections in Domain Objects

    • Must alwa s use Interfaces

     – Collection, List, Map, Set, etc…•  

     –  Not delegated to Constructor, Setter, …

    List mylist = new ArrayList()

    Mapping Multiplicity

    • 1:M/M:1

     –  Example: EBiller has many EBills / EBill has one EBiller 

     –  On the ‘one’ side, map the Collection objects (EBiller) 

     –  On the ‘many’ side, map the single object (EBill)•   • M:M

     –  Example: Account has many EBillers / EBiller has manyAccounts

     –  On both sides, map the Collection objects•  

    •  

    • Only required on both sides if the relationship is bidirectional

  • 8/16/2019 03-Hibernate-Association and Collection Mapping

    12/27

    Mapping Multiplicity 1:1

    • UNINTUITIVE MAPPING!

      –  EBill has at most one AccountTransaction

     –  AccountTransaction has at most one EBill

     –   

    • In the NON-STORING Entity mapping file (AccountTransaction)– 

    • In the STORING Entity mapping file (EBill)– 

    • Enforce one-to-one in the database with unique constraints

    • If storing foreign keys on both sides, use two many-to-one tags.

    Java-to-Database

    • Association & Collection mapping tagspractically identical

    • Hibernate Collection Types – 

    • Unordered/Ordered, requiring value column – 

    • Unordered/Ordered, requiring key and valueco umns

     – 

    • r ere , requ r ng an n ex co umn on ereferenced object table

  • 8/16/2019 03-Hibernate-Association and Collection Mapping

    13/27

    Java-to-Database Through Hibernate

     –  

    • Ordered, requiring an index column on thereferenced object table

     – • No direct implementation available in Java•  • Realized through Collection/List• Requires value column

     – < ag>

    • Used for many-to-many relationships•   ,column used for surrogate keys

    • Requires an ID Generator just like Entity classes

    Association as

    • Maps to a ‘Set’ interface –  Imp s nc u e Has Set, TreeSet, etc…

    • Can be optionally sorted

    er as many s : :

    EBill Mapping

    EBiller Mapping

  • 8/16/2019 03-Hibernate-Association and Collection Mapping

    14/27

    Association as

    • Maps to a ‘Map’ interface –    , , …

    • Must identify a column to be used for map key –  Can be ‘column’, or ‘formula’ (any sql expression)• an e op ona y sor e

    EBiller has many EBills (1:M / M:1)

     

    er app ng

    Association as

    • Maps to a ‘List’ interface –    , , …

    •   MUST have a dedicated list-index columnon table –  equen a or er ng o ems or e paren spec e –  Skipped numbers result in Null values in list

    EBiller has many EBills (1:M / M:1)

    EBill Mapping

    EBiller Mapping

  • 8/16/2019 03-Hibernate-Association and Collection Mapping

    15/27

    Association as

    • Like ‘List’, Arrays MUST have a dedicatedlist-index column on table

    EBiller has many EBills (1:M / M:1)

    EBill Mapping

  • 8/16/2019 03-Hibernate-Association and Collection Mapping

    16/27

    Association as

    • Same as ‘Bag’ – but only used in many-to-many relationships –  Allows for mapping of surrogate keys on join table –  ernate w set t e on t e o n ta e –  Can  NOT use idbag on both sides of the relationship! Non-idbag side must have

    inverse=“true”• Can be optionally sorted

    er as many ccoun s ccoun as many ers :

    EBill Mapping

    Account Mapping" " " "

    Remember inverse=true on ‘non-idbag’ side?

      _order-by="DUE_DATE ASC" >

    Collection Mapping

    • Can be used across all mapping types –   

    < ag

  • 8/16/2019 03-Hibernate-Association and Collection Mapping

    17/27

    Bidirectional Maintenance

    • Develo ers must maintainbidirectional associations in order tokee in-memor ob ects u -to-date

    aParent.getChildren().add(aChild);

    .

    • erna e recommen s a s ra egy o

    ensure this process.

    Hibernate’s Bidirectional Strategy

    • Maintain associations on a single side of the relationship

    ‘ ’

    • Create ‘addObject’ method instead ofobject.getMySet().add(object); –    ,

    • p.120 of Java Persistence with Hibernate

    Example EBiller  EBill (1:M/M:1)

    : protected void setEBiller(EBiller ebiller) {

    this.ebiller = ebiller;}

    EBiller (1:M) public void addEBill(EBill ebill) {

    if (!ebill.getEBiller().equals(this) {

    }ebill.setEBiller(this);this.ebills.add(ebill);

  • 8/16/2019 03-Hibernate-Association and Collection Mapping

    18/27

    Modified Hibernate Strategy

    • Hibernate strategy might not solve all cases

     –  e a e o ec s are requ re o e n e same pac age

     – Developers need to remember which object to call•  

     – Maintain relationship on either side

     – Slightly varying implementations required for differentrelationship types

    • 1:1

     – Collections on both sides

    • 1:M/M:1 – has single object that can potentially be null

    • Collections should always be instantiated (early) – sonever null

    Modified Bidirectional Strategy 1:1

    • Need to handle potential null object on each side –  Ob ects mi ht not be initialized 

    Example: EBill has one Transaction / Transaction has one EBill

    EBill Set Method public void setTransaction(Transaction transaction) {

    this.transaction = transaction;if (transaction != null &&

    (transaction.getEbill() == null ||!transaction.getEbill().equals(this))) {

    transaction.setEbill(this);}

    } Transaction Set Method public void setEbill(EBill ebill) {

    this.ebill = ebill;if (ebill != null &&

    (ebill.getTransaction() == null ||!ebill.getTransaction().equals(this))) {

    ebill.setTransaction(this);}

    }

  • 8/16/2019 03-Hibernate-Association and Collection Mapping

    19/27

    Modified Bidirectional Strategy M:M

    • Protected Setters for Collections on both sides• Do not need to handle null checks

     –  Collections should be initialized early

    Example: Account has many EBillers / EBiller has many AccountsEBiller Set Method

     protected void setAccounts(List accounts) {this.accounts = accounts;

    }

    EBiller Add Method public void addAccount(Account account){

    this.accounts.add(account);if (!account.getEbillers().contains(this)) {account.addEbiller(this);

    EBiller Remove Method

     public void removeAccount(Account account) {this.accounts.remove(account);

    }}

    if (account.getEbillers().contains(this)) {account.removeEbiller(this);

    }}

    Modified Bidirectional Strategy M:M• Protected Setters for Collections on both sides• Do not need to handle null checks

     –  Collections should be initialized early

    Example: Account has many EBillers / EBiller has many Accounts

     Account Setter 

     Account Add Method

     protected void setEbillers(List ebillers) {this.ebillers = ebillers;

    }

     public void addEbiller(EBiller ebiller) {this.ebillers.add(ebiller);if (!ebiller.getAccounts().contains(this)) {ebiller.addAccount(this);

     Account Remove Method public void removeEbiller(EBiller ebiller) {

    this.ebillers.remove(ebiller);

    }}

    if (ebiller.getAccounts().contains(this)) {ebiller.removeAccount(this);

    }}

  • 8/16/2019 03-Hibernate-Association and Collection Mapping

    20/27

    Modified Bidirectional Strategy 1:M

    • Protected Setter for Collection• Need to handle null check on non-Collection side

     –  Object may not have been initialized

    Example: EBiller has many EBills / EBill has one EBiller 

    EBill Setter  public void setEbiller(EBiller ebiller) {

    this.ebiller = ebiller;if (ebiller != null && !ebiller.getEbills().contains(this)) {ebiller.addEbill(this);

    }}

    Modified Bidirectional Strategy 1:M

    • Protected Setter for Collection• Need to handle null check on non-Collection side

     –  Object may not have been initialized

    Example: EBiller has many EBills / EBill has one EBiller 

    EBiller Set Method protected void setEbills (SortedSet ebills) {

    this.ebills = ebills;}

    EBiller Add Method this.ebills.add(ebill);if (!ebill.getEBiller().equals(this) {

    ebill.getEBiller().getEBills().remove(ebill).

    }}

    EBiller Remove Method public void removeEbill(EBill ebill) {

    ebills.remove(ebill);if (ebill.getEbiller().equals(this)) {ebill.setEbiller(null);

    }}

  • 8/16/2019 03-Hibernate-Association and Collection Mapping

    21/27

    Bidirectional Concern

    • Recursive Issue

     –   themselves during method execution

     –  Can result in StackOverflowException• hash ode

    • toString()

    • equals()

    • erna e s s ra egy or se ng rec ona y

     –  Hibernate recommends NOT using associate objects in thesemethods

     –  For 1:M, on the many side, set ‘access by field’ on the tag.

    •  complicated and overly involved to handle

     –  Ask yourself, does this really need to be bidirectional?

    © 2009 coreservlets.com

    ona : p ons

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

  • 8/16/2019 03-Hibernate-Association and Collection Mapping

    22/27

    Many-to-Many Option

    • Hibernate actually recommends not us ng tra t ona many-to-many

    relationships• Proposes use of “Intermediate

    Associations” – Relationships often have data directly tied to

    them. If not, likely to later, so might as well start

     – “Intermediate” object to map the relationship –   • Composite element

    • Entity class

    Intermediate Association:

    • Customer:Contractor (M:M)

    • aren o ec con a ns a o ec on o on racobjects

     –  Each “Contract” object contains the Customer, Contractor, anddata about the relationship (start date, contract price, etc…)

    MAPPING FOR CUSTOMER

    " " " " " "= = =

  • 8/16/2019 03-Hibernate-Association and Collection Mapping

    23/27

    Intermediate Association:

    • Advantages –   

     parent object

    • To create an association, add a new Contract to theCollection

    Contract aContract =new Contract(aCustomer, aContractor);

    aCustomer.getContracts().add(aContract);

    • To delete, remove from Collection– aCustomer.getContracts().remove(aContract);

    • – Bidirectional navigation is impossible

    • Composite element only exists within the context of thearent class• However – can write a query to retrieve the objects you

    need

    Intermediate Association:

    • Customer:Contractor (M:M) –    - -

    • Each side contains a Collection of Contractobjects –  ac on rac o ec con a ns e us omer,

    Contractor, and data about the relationship (start

    date, contract price, etc…)MAPPING FOR CUSTOMER

    MAPPING FOR CONTRACTOR

    " "_

  • 8/16/2019 03-Hibernate-Association and Collection Mapping

    24/27

    Intermediate Association:

    MAPPING FOR CONTRACT (Relationship Entity)  = = _ mutable="false">

    - - =" " =" "  _

    not-null="true" update="false"/>

    NOTICE CONTRACT HAS ITS OWN ID – (Think “Entity”)

    Intermediate Association:

    • Advantages –   

    • Both objects obtain other through ContractaContractor.getContracts()

    aCustomer.getContracts()

    • Disadvantages –  No direct access to collection on other side (need to loop through all

    the Contract objects to build collection) –  More complex code needed to manage the Contract entity instance

    to create and remove associations• Requires additional infrastructure code

     – n y ass on rac

     – Identifier 

    • Intermediate class has to be saved and deleted independently tocreate links between ob ects

    Contract aContract = newContract(aCustomer.getCustomerId(),aContractor.getContractorId());

    session.save(aContract);

  • 8/16/2019 03-Hibernate-Association and Collection Mapping

    25/27

    Ternary Relationships

    • Relationshi across three ob ects 

    • Leverage the Intermediate Association toinclude a reference to an additional thirdEntity

    Customer  Contractor Contract

    Sales Rep

    Ternary Relationships

    MAPPING FOR CONTRACT (Relationship Entity)

  • 8/16/2019 03-Hibernate-Association and Collection Mapping

    26/27

    © 2009 coreservlets.com

    rap-up

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at your location.

    Summary

    In this lecture, we:•  

    between Entity classes and Collections are justgroupings of scalar data

     relationships

     –  Java: Object references –  a a ases: enorma ze a es, ore gn eys, o n a es,and ad hoc joins

    • Walked through the ways to realize

     – Setting up the mapping files – Coding to Interfaces

    •  approaches using an ‘intermediate’ object torealize M:M and ternary relationships

  • 8/16/2019 03-Hibernate-Association and Collection Mapping

    27/27

    Preview of Next Sections

    • Understand the differences

    between Component & Entityclasses

    • Learn how to map Components

    •  inheritance

    54

    © 2009 coreservlets.com

    ues ons