Question

Isn't it possible to map xml to jpa entities using JAXB? Will Eclipselink Moxy be helpful?

Was it helpful?

Solution

Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 (JSR-222) expert group.

Yes you can map JPA entities to XML, and the following are some ways that EclipseLink JAXB (MOXy) makes this easier.

1. Bidirectional Mappings

Customer

import javax.persistence.*;

@Entity
public class Customer {

    @Id
    private long id;

    @OneToOne(mappedBy="customer", cascade={CascadeType.ALL})
    private Address address;

}

Address

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;

}

For More Information

 

2. Mapping Compound Key Relationships

We normally think of mapping a tree of objects to XML, however JAXB supports using the combination of @XmlID/@XmlIDREF to map relationship between nodes representing a graph. The standard mechanism is one key, to one foreign key. JPA supports the concept of composite keys and so does MOXy using @XmlKey and @XmlJoinNodes (similar to @XmlJoinColumns in JPA).

Employee

@Entity
@IdClass(EmployeeId.class)
public class Employee {

    @Id
    @Column(name="E_ID")
    @XmlID
    private BigDecimal eId;

    @Id
    @XmlKey
    private String country;

    @OneToMany(mappedBy="contact")
    @XmlInverseReference(mappedBy="contact")
    private List<PhoneNumber> contactNumber;

}

PhoneNumber

@Entity
public class PhoneNumber {

    @ManyToOne
    @JoinColumns({
        @JoinColumn(name="E_ID", referencedColumnName = "E_ID"),
        @JoinColumn(name="E_COUNTRY", referencedColumnName = "COUNTRY")
    })
    @XmlJoinNodes( {
        @XmlJoinNode(xmlPath="contact/id/text()", referencedXmlPath="id/text()"),
        @XmlJoinNode(xmlPath="contact/country/text()", referencedXmlPath="country/text()")
    })
    private Employee contact;

}

For More Information

 

3. MOXy allows for Composite and Embedded Keys

JPA can also use embedded key classes to represent composite keys. MOXy also supports this style of composite keys.

For More Information

 

4. EclipseLink JAXB (MOXy) and EclipseLink JPA Have Shared Concepts

EclipseLink provides both JAXB and JPA implementations that share a common core. This means that they share many of the same concepts, such as:

Virtual Access Methods

EclipseLink supports the concept of virtual properties. This is useful when creating a multi-tenant application where you want per-tenant customizations. This concept is upported in both EclipseLink's JPA and JAXB implementations.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top