Showing posts with label JAXBElement. Show all posts
Showing posts with label JAXBElement. Show all posts

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.

July 30, 2012

JAXB - No Annotations Required

There appears to be a misconception that annotations are required on the model in order to use a JAXB (JSR-222) implementation.  The truth is that JAXB is configuration by exception, so annotations are only required when you want to override default behaviour.  In this example I'll demonstrate how to use JAXB without providing any metadata.

February 11, 2012

Mapping an Arbitrary List of Objects using JAXB's @XmlAnyElement and XmlAdapter

The @XmlAnyElement annotation enables a property to handle arbitrary XML elements, and the XmlAdapter provides a way to convert an object that can not be mapped into one that can.  In this post we will combine these two mechanisms  to map a list of arbitrary objects.

This post will cover the following concepts:
  1. The @XmlAnyElement annotation
  2. A type level XmlAdapter
  3. Marshalling/Unmarshalling root level simple data types (i.e. String and Integer)
  4. Specifying a root element via JAXBElement
  5. Specifying the type to be unmarshalled on the Unmarshaller

March 8, 2011

Using JAXB to Implement a Copy Operation

The following post was inspired by an answer I gave to a question on Stack Overflow (feel free to up vote).  I am not suggesting that JAXB should be used to implement copy methods, instead I'm using a copy operation to demonstrate that JAXB can treat an object model as XML input.