JAXB and Unmapped Properties

JAXB (JSR-222) is configuration by exception, meaning that there is a default mapping applied to domain objects. This means that sometimes you need to explicitly exclude a field/property. In this post I’ll discuss how this can be done using @XmlTransient or @XmlAccessorType(XmlAccessType.NONE) and when each option is appropriate.

@XmlTransient

package blog.unmapped; 

import java.util.List;
import javax.xml.bind.annotation.*; 

@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
    @XmlTransient
    private int id; 

    private String firstName;

    private String lastName; 

    private Address billingAddress; 

    private Address shippingAddress; 

    private List<PhoneNumber> phoneNumbers;

The resultant XML will not have the “id” field inside it.

If more than half of the fields/properties are unmapped then we stop gaining the benefit of configuration by exception since we need to do more work to exclude properties with @XmlTransient than we would have had to do to map the mapped properties.

To Resolve this problem, JAXB comes with a new flavor of annotation –

@XmlAccessorType(XmlAccessType.NONE)

package blog.unmapped;

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.NONE)
public class Customer {
    private int id;

    @XmlElement
    private String firstName;

    @XmlElement
    private String lastName;

    private Address billingAddress;

    private Address shippingAddress;

    private List<PhoneNumber> phoneNumbers;
}

The resultant XML file will not have those elements which are not explicitly mapped using the @XmlElement annotation.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s