JAXB and Unmapped Properties
@XmlTransient
When you mark a field/property with @XmlTransient you are explicitly telling your JAXB implementation to treat it as an unmapped property. This is useful when less than half of the fields/properties are unmapped.
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; }
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. Next I’ll demonstrate how we can leverage @XmlAccessorType(XmlAccessType.NONE) for this use case.
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; @XmlTransient private Address billingAddress; @XmlTransient private Address shippingAddress; @XmlTransient private List<PhoneNumber> phoneNumbers; }
@XmlAccessorType(XmlAccessType.NONE)
By setting @XmlAccessorType(XmlAccessType.NONE) we are disabling configuration by exception. Now only explicitly mapped properties will be mapped. This is useful when less than half of the fields/properties of a domain object are mapped.
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; @XmlTransient private Address billingAddress; @XmlTransient private Address shippingAddress; @XmlTransient private List<PhoneNumber> phoneNumbers; }
Further Reading
If you enjoyed this post then you also like:
- Using JAXB’s @XmlAccessorType to Configure Field or Property Access
- Ignoring Inheritance with @XmlTransient
Reference: JAXB and Unmapped Properties from our JCG partner Blaise Doughan at the Java XML & JSON Binding blog.
Your last example with @XmlAccessorType(XmlAccessType.NONE) doesn’t do what it claims. You still have marked the fields @XMLTransient. Besides how does one explicitly mark a property?
Looks like the code snippet for @XmlAccessorType(XmlAccessType.NONE) is wrong, may be copy paste error?