August 16, 2012

Removing JAXBElement From Your Domain Model

JAXBElement is a JAXB (JSR-222) mechanism that stores name and namespace information in situations where this can not be determined from the value or mapping.  For example in the class below the elements billing-address and shipping-address both correspond to the Address class.  In order to be able to round trip the data we need to keep track of which element we unmarshalled.
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {

    @XmlElementRefs({
        @XmlElementRef(name = "billing-address"),
        @XmlElementRef(name = "shipping-address")
    })
    private JAXBElement<Address> address;

}
While useful JAXBElement can get in the way if you want to use your domain model with something like JPA (which doesn't know what to do with it).  In this post I will demonstrate how you can eliminate the need for JAXBElement through the use of an XmlAdapter.

August 12, 2012

Handle the Middle of a XML Document with JAXB and StAX

Recently I have come across a lot of people asking how to read data from, or write data to the middle of an XML document.  In this post I will demonstrate how this can be done using JAXB with StAX.  Note:  JAXB (JSR-222) and StAX (JSR-173) implementations are included in the JDK/JRE since Java SE 6.

August 11, 2012

JAXB's @XmlTransient and Property Order

In previous articles I wrote about how the @XmlTransient annotation can be used at the type level to have a class excluded from the inheritance hierarchy, or at the field/property level to unmap a field/property.  In this article I'll demonstrate how doing this impacts the propOrder setting on the @XmlType annotation.