Difference between revisions of "EclipseLink/UserGuide/MOXy/Relationships/Bidirectional Relationships"

From Eclipsepedia

Jump to: navigation, search
m (Bidirectional Relationships)
Line 2: Line 2:
 
|info=y
 
|info=y
 
|api=y
 
|api=y
|apis=* [http://www.eclipse.org/eclipselink/api/latest/org/eclipse/persistence/mappings/XMLTransient.html XMLTransient]
+
|apis= * [http://www.eclipse.org/eclipselink/api/latest/org/eclipse/persistence/oxm/annotations/XmlInverseReference.html XmlInverseReference]
* [http://www.eclipse.org/eclipselink/api/latest/org/eclipse/persistence/mappings/XMLInverseReferenceMapping.html XMLInverseReferenceMapping]
+
 
}}  
 
}}  
 
= Bidirectional Relationships  =
 
= Bidirectional Relationships  =

Revision as of 13:03, 19 April 2011


link="http://wiki.eclipse.org/EclipseLink"
EclipseLink
Website
Download
Community
Mailing ListForumsIRC
Bugzilla
Open
Help Wanted
Bug Day
Contribute
Browse Source

Bidirectional Relationships

When binding JPA entities to XML, there are MOXy extensions will help you map a bidirectional relationship.

In this sample model, notice that Customer has a relationship to Address, and Address has a relationship back to Customer. In JPA, one direction of the relationship is mapped (the customer property on Address); the other direction specifies a mapping to leverage.

Sample Model

 
import javax.persistence.*;
 
@Entity
public class Customer {
 
    @Id
    private long id;
 
    @OneToOne(mappedBy="customer", cascade={CascadeType.ALL})
    private Address address;
 
}
 
 
import javax.persistence.*;
 
@Entity
public class Address implements Serializable {
 
    @Id
    private long id;
 
    @MapsId
    @OneToOne
    @JoinColumn(name="ID")
    private Customer customer;
 
}

To marshal these objects to XML, mark one direction @XmlTransient' to prevent a JAXB infinite loop during marshalling. Normally, during unmarshalling (from XML-to-object), you are responsible for populating the back pointer

 
import javax.persistence.*;
import javax.xml.bind.annotation.*;
 
@Entity
public class Address implements Serializable {
 
    @Id
    private long id;
 
    @OneToOne
    @JoinColumn(name="ID")
    @MapsId
    @XmlTransient
    private Customer customer;
 
}


@XMLInverseReference

With the @XmlInverseReference annotation, MOXy will populate the back pointer automatically. In this sample, notice that the @XmlInverseReference annotation leverages the same "mappedBy" concept.

 
import javax.persistence.*;
import org.eclipse.persistence.oxm.annotations.*;
 
@Entity
public class Address implements Serializable {
 
    @Id
    private long id;
 
    @OneToOne
    @JoinColumn(name="ID")
    @MapsId
    @XmlInverseReference(mappedBy="address")
    private Customer customer;
 
}


Eclipselink-logo.gif
Version: 2.2.0 DRAFT
Other versions...