Java-to-Schema Examples
The Java-to-Schema examples show how to use annotations to map Java classes to XML schema.
j2s-create-marshal Example
The
j2s-create-marshal
example illustrates Java-to-schema databinding. It demonstrates marshalling and unmarshalling of JAXB annotated classes and also shows how to enable JAXP 1.3 validation at unmarshal time using a schema file that was generated from the JAXB mapped classes.The schema file,
bc.xsd
, was generated with the following commands:Note that
schema1.xsd
, was copied tobc.xsd
;schemagen
does not allow you to specify a schema name of your choice.Building and Running the j2s-create-marshal Example Using NetBeans 5.5
Follow these instructions to build and run the
j2s-create-marshal
example on your Application Server instance using the NetBeans 5.5 IDE.Building and Running the j2s-create-marshal Example Using Ant
To compile and run the
j2s-create-marshal
example using Ant, in a terminal window, go to the<INSTALL>
/javaeetutorial5/examples/jaxb/j2s-create-marshal/
directory and type the following:j2s-xmlAccessorOrder Example
The
j2s-xmlAccessorOrder
example shows how to use the@XmlAccessorOrder
and@XmlType.propOrder
annotations to dictate the order in which XML content is marshalled/unmarshalled by a Java type.With Java-to-schema mapping, a JavaBean's properties and fields are mapped to an XML Schema type. The class elements are mapped to either an XML Schema complex type or an XML Schema simple type. The default element order for a generated schema type is currently unspecified because Java reflection does not impose a return order. The lack of reliable element ordering negatively impacts application portability. You can use two annotations,
@XmlAccessorOrder
and@XmlType.propOrder
, to define schema element ordering for applications that need to be portable across JAXB Providers.Using the @XmlAccessorOrder Annotation to Define Schema Element Ordering
The
@XmlAccessorOrder
annotation imposes one of two element ordering algorithms,AccessorOrder.UNDEFINED
orAccessorOrder.ALPHABETICAL
.AccessorOrder.UNDEFINED
is the default setting. The order is dependent on the system's reflection implementation.AccessorOrder.ALPHABETICAL
orders the elements in lexicographic order as determined byjava.lang.String.CompareTo(String anotherString)
.You can define the
@XmlAccessorOrder
annotation for annotation typeElementType.PACKAGE
on a class object. When the@XmlAccessorOrder
annotation is defined on a package, the scope of the formatting rule is active for every class in the package. When defined on a class, the rule is active on the contents of that class.There can be multiple
@XmlAccessorOrder
annotations within a package. The order of precedence is the innermost (class) annotation takes precedence over the outer annotation. For example, if@XmlAccessorOrder(AccessorOrder.ALPHABETICAL)
is defined on a package and@XmlAccessorOrder(AccessorOrder.UNDEFINED)
is defined on a class in that package, the contents of the generated schema type for the class would be in an unspecified order and the contents of the generated schema type for every other class in the package would be alphabetical order.Using the @XmlType Annotation to Define Schema Element Ordering
The
@XmlType
annotation can be defined for a class. The annotation elementpropOrder()
in the@XmlType
annotation allows you to specify the content order in the generated schema type. When you use the@XmlType.propOrder
annotation on a class to specify content order, all public properties and public fields in the class must be specified in the parameter list. Any public property or field that you want to keep out of the parameter list must be annotated with@XmlAttribute
or@XmlTransient
annotation.The default content order for
@XmlType.propOrder
is {} or {""}, not active. In such cases, the active@XmlAccessorOrder
annotation takes precedence. When class content order is specified by the@XmlType.propOrder
annotation, it takes precedence over any active@XmlAccessorOrder
annotation on the class or package. If the@XmlAccessorOrder
and@XmlType.propOrder(A, B, ...)
annotations are specified on a class, thepropOrder
always takes precedence regardless of the order of the annotation statements. For example, in the code below, the@XmlAccessorOrder
annotation precedes the@XmlType.propOrder
annotation.@XmlAccessorOrder(AccessorOrder.ALPHABETICAL) @XmlType(propOrder={"name", "city"}) public class USAddress { . . public String getCity() {return city;} public void setCity(String city) {this.city = city;} public String getName() {return name;} public void setName(String name) {this.name = name;} . . }In the code below, the
@XmlType.propOrder
annotation precedes the@XmlAccessorOrder
annotation.@XmlType(propOrder={"name", "city"}) @XmlAccessorOrder(AccessorOrder.ALPHABETICAL) public class USAddress { . . public String getCity() {return city;} public void setCity(String city) {this.city = city;} public String getName() {return name;} public void setName(String name) {this.name = name;} . . }In both scenarios,
propOrder
takes precedence and the identical schema content shown below will be generated.<xs:complexType name="usAddress"> <xs:sequence> <xs:element name="name" type="xs:string" minOccurs="0"/> <xs:element name="city" type="xs:string" minOccurs="0"/> </xs:sequence> </xs:complexType>Schema Content Ordering in the Example
The purchase order code example demonstrates the effects of schema content ordering using the
@XmlAccessorOrder
annotation at the package and class level, and the@XmlType.propOrder
annotation on a class.Class
package-info.java
defines@XmlAccessorOrder
to beALPHABETICAL
for the package. The public fieldsshipTo
andbillTo
in classPurchaseOrderType
will be affected in the generated schema content order by this rule. ClassUSAddress
defines the@XmlType.propOrder
annotation on the class. User of this annotation demonstrates user-defined property order supersedingALPHABETICAL
order in the generated schema.The generated schema file can be found in the
<INSTALL>
/javaeetutorial5/examples/jaxb/j2s-xmlAccessorOrder/build/schemas/
directory.Building and Running the j2s-xmlAccessorOrder Example Using
NetBeans 5.5Follow these instructions to build and run the
j2s-xmlAccessorOrder
example on your Application Server instance using the NetBeans 5.5 IDE.
- In NetBeans 5.5, select File
Open Project.
- In the Open Project dialog, navigate to
<
INSTALL
>/javaeetutorial5/examples/jaxb/
.- Select the
j2s-xmlAccessorOrder
folder.- Select the Open as Main Project checkbox.
- Click Open Project Folder.
- Right-click the
j2s-xmlAccessorOrder
project and select Run Project.Building and Running the j2s-xmlAccessorOrder Example Using Ant
To compile and run the
j2s-xmlAccessorOrder
example using Ant, in a terminal window, go to the<INSTALL>
/javaeetutorial5/examples/jaxb/j2s-xmlAccessorOrder/
directory and type the following:j2s-xmlAdapter-field Example
The
j2s-xmlAdapter-field
example demonstrates how to use theX
mlAdapter
interface and the@XmlJavaTypeAdapter
annotation to provide a custom mapping of XML content into and out of aHashMap
(field) that uses anint
as the key and aString
as the value.Interface
XmlAdapter
and annotation@XmlJavaTypeAdapter
are used for special processing of datatypes during unmarshalling/marshalling. There are a variety of XML datatypes for which the representation does not map easily into Java (for example,xs:DateTime
andxs:Duration
), and Java types which do not map conveniently into XML representations, for example implementations ofjava.util.Collection
(such asList
) andjava.util.Map
(such asHashMap
) or for non-JavaBean classes.The
XmlAdapter
interface and the@XmlJavaTypeAdapter
annotation are provided for cases such as these. This combination provides a portable mechanism for reading/writing XML content into and out of Java applications.The
XmlAdapter
interface defines the methods for data reading/writing./* * ValueType - Java class that provides an XML representation * of the data. It is the object that is used for * marshalling and unmarshalling. * * BoundType - Java class that is used to process XML content. */ public abstract class XmlAdapter<ValueType,BoundType> { // Do-nothing constructor for the derived classes. protected XmlAdapter() {} // Convert a value type to a bound type. public abstract BoundType unmarshal(ValueType v); // Convert a bound type to a value type. public abstract ValueType marshal(BoundType v); }You can use the
@XmlJavaTypeAdapter
annotation to associate a particularXmlAdapter
implementation with aTarget
type,PACKAGE
,FIELD
,METHOD
,TYPE
, orPARAMETER
.The
j2s-xmlAdapter-field
example shows how to use anXmlAdapter
for mapping XML content into and out of a (custom)HashMap
. TheHashMap
object,basket
, in classKitchenWorldBasket
, uses a key of typeint
and a value of typeString
. We want these datatypes to be reflected in the XML content that is read and written. The XML content should look like this.<basket> <entry key="9027">glasstop stove in black</entry> <entry key="288">wooden spoon</entry> </basket>The default schema generated for Java type
HashMap
does not reflect the desired format.<xs:element name="basket"> <xs:complexType> <xs:sequence> <xs:element name="entry" minOccurs="0" maxOccurs="unbounded"> <xs:complexType> <xs:sequence> <xs:element name="key" minOccurs="0" type="xs:anyType"/> <xs:element name="value" minOccurs="0" type="xs:anyType"/> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element>In the default
HashMap
schema, key and value are both elements and are of datatypeanyType
. The XML content will look like this:<basket> <entry> <key>9027</> <value>glasstop stove in black</> </entry> <entry> <key>288</> <value>wooden spoon</> </entry> </basket>To resolve this issue, we wrote two Java classes,
PurchaseList
andPartEntry
, that reflect the needed schema format for unmarshalling/marshalling the content. The XML schema generated for these classes is as follows:<xs:complexType name="PurchaseListType"> <xs:sequence> <xs:element name="entry" type="partEntry" nillable="true" maxOccurs="unbounded" minOccurs="0"/> </xs:sequence> </xs:complexType> <xs:complexType name="partEntry"> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute name="key" type="xs:int" use="required"/> </xs:extension> </xs:simpleContent> </xs:complexType>Class
AdapterPurchaseListToHashMap
implements theXmlAdapter
interface. In classKitchenWorldBasket
, the@XmlJavaTypeAdapter
annotation is used to pairAdapterPurchaseListToHashMap
with fieldHashMap
basket
. This pairing will cause the marshal/unmarshal method ofAdapterPurchaseListToHashMap
to be called for any corresponding marshal/unmarshal action onKitchenWorldBasket
.Building and Running the j2s-xmlAdapter-field Example Using NetBeans 5.5
Follow these instructions to build and run the
j2s-xmlAdapter-field
example on your Application Server instance using the NetBeans 5.5 IDE.
- In NetBeans 5.5, select File
Open Project.
- In the Open Project dialog, navigate to
<
INSTALL
>/javaeetutorial5/examples/jaxb/
.- Select the
j2s-xmlAdapter-field
folder.- Select the Open as Main Project checkbox.
- Click Open Project Folder.
- Right-click the
j2s-xmlAdapter-field
project and select Run Project.Building and Running the j2s-xmlAdapter-field Example Using Ant
To compile and run the
j2s-xmlAdapter-field
example using Ant, in a terminal window, go to the<INSTALL>
/javaeetutorial5/examples/jaxb/j2s-xmlAdapter-field/
directory and type the following:j2s-xmlAttribute-field Example
The
j2s-xmlAttribute-field
example shows how to use the@XmlAttribute
annotation to define a property or field to be treated as an XML attribute.The
@XmlAttribute
annotation maps a field or JavaBean property to an XML attribute. The following rules are imposed:When following the JavaBean programming paradigm, a property is defined by a
get
andset
prefix on a field name.Within a bean class, you have the choice of setting the
@XmlAttribute
annotation on one of three components: the field, the setter method, or the getter method. If you set the@XmlAttribute
annotation on the field, the setter method will need to be renamed or there will be a naming conflict at compile time. If you set the@XmlAttribute
annotation on one of the methods, it must be set on either the setter or getter method, but not on both.The
j2s-xmlAttribute-field
example shows how to use the@XmlAttribute
annotation on a static final field, on a field rather than on one of the corresponding bean methods, on a bean property (method), and on a field that is other than a collection type. In classUSAddress
, fields, country, and zip are tagged as attributes. ThesetZip
method was disabled to avoid the compile error. Property state was tagged as an attribute on the setter method. You could have used the getter method instead. In classPurchaseOrderType
, fieldcCardVendor
is a non-collection type. It meets the requirement of being a simple type; it is anenum
type.Building and Running the j2s-xmlAttribute-field Example Using NetBeans 5.5
Follow these instructions to build and run the
j2s-xmlAttribute-field
example on your Application Server instance using the NetBeans 5.5 IDE.
- In NetBeans 5.5, select File
Open Project.
- In the Open Project dialog, navigate to
<
INSTALL
>/javaeetutorial5/examples/jaxb/
.- Select the
j2s-xmlAttribute-field
folder.- Select the Open as Main Project checkbox.
- Click Open Project Folder.
- Right-click the
j2s-xmlAttribute-field
project and select Run Project.Building and Running the j2s-xmlAttribute-field Example Using Ant
To compile and run the
j2s-xmlAttribute-field
example using Ant, in a terminal window, go to the<INSTALL>
/javaeetutorial5/examples/jaxb/j2s-xmlAttribute-field/
directory and type the following:j2s-xmlRootElement Example
The
j2s-xmlRootElement
example demonstrates the use of the@XmlRootElement
annotation to define an XML element name for the XML schema type of the corresponding class.The
@XmlRootElement
annotation maps a class or anenum
type to an XML element. At least one element definition is needed for each top-level Java type used for unmarshalling/marshalling. If there is no element definition, there is no starting location for XML content processing.The
@XmlRootElement
annotation uses the class name as the default element name. You can change the default name by using the annotation attributename
. If you do, the specified name will then be used as the element name and the type name. It is common schema practice for the element and type names to be different. You can use the@XmlType
annotation to set the element type name.The namespace attribute of the
@XmlRootElement
annotation is used to define a namespace for the element.Building and Running the j2s-xmlRootElement Example Using NetBeans 5.5
Follow these instructions to build and run the
j2s-xmlRootElement
example on your Application Server instance using the NetBeans 5.5 IDE.Building and Running the j2s-xmlRootElement Example Using Ant
To compile and run the
j2s-xmlRootElement
example using Ant, in a terminal window, go to the<INSTALL>
/javaeetutorial5/examples/jaxb/j2s-xmlRootElement/
directory and type the following:j2s-xmlSchemaType-class Example
The
j2s-xmlSchemaType-class
example demonstrates the use of the annotation@XmlSchemaType
to customize the mapping of a property or field to an XML built-in type.The
@XmlSchemaType
annotation can be used to map a Java type to one of the XML built-in types. This annotation is most useful in mapping a Java type to one of the nine date/time primitive datatypes.When the
@XmlSchemaType
annotation is defined at the package level, the identification requires both the XML built-in type name and the corresponding Java type class. An@XmlSchemaType
definition on a field or property takes precedence over a package definition.The
j2s-xmlSchemaType-class
example shows how to use the@XmlSchemaType
annotation at the package level, on a field, and on a property. FileTrackingOrder
has two fields,orderDate
anddeliveryDate
, which are defined to be of typeXMLGregorianCalendar
. The generated schema will define these elements to be of XML built-in typegMonthDay
. This relationship was defined on the package in the filepackage-info.java
. FieldshipDate
in fileTrackingOrder
is also defined to be of typeXMLGregorianCalendar
, but the@XmlSchemaType
annotation statements override the package definition and specify the field to be of typedate
. Property methodgetTrackingDuration
defines the schema element to be defined as primitive typeduration
and not Java typeString
.Building and Running the j2s-xmlSchemaType-class Example Using NetBeans 5.5
Follow these instructions to build and run the
j2s-xmlSchemaType-class
example on your Application Server instance using the NetBeans 5.5 IDE.
- In NetBeans 5.5, select File
Open Project.
- In the Open Project dialog, navigate to
<
INSTALL
>/javaeetutorial5/examples/jaxb/
.- Select the
j2s-xmlSchemaType-class
folder.- Select the Open as Main Project checkbox.
- Click Open Project Folder.
- Right-click the
j2s-xmlSchemaType-class
project and select Run Project.Building and Running the j2s-xmlSchemaType-class Example Using Ant
To compile and run the
j2s-xmlSchemaType-class
example using Ant, in a terminal window, go to the<INSTALL>
/javaeetutorial5/examples/jaxb/j2s-xmlSchemaType-class/
directory and type the following:j2s-xmlType Example
The
j2s-xmlType
example demonstrates the use of the@XmlType
annotation. The@XmlType
annotation maps a class or anenum
type to a XML Schema type.A class must have either a public zero arg constructor or a static zero arg factory method in order to be mapped by this annotation. One of these methods is used during unmarshalling to create an instance of the class. The factory method may reside within in a factory class or the existing class. There is an order of precedence as to which method is used for unmarshalling:
- If a factory class is identified in the annotation, a corresponding factory method in that class must also be identified and that method will be used.
- If a factory method is identified in the annotation but no factory class is identified, the factory method must reside in the current class. The factory method is used even if there is a public zero arg constructor method present.
- If no factory method is identified in the annotation, the class must contain a public zero arg constructor method.
In this example, a factory class provides zero arg factory methods for several classes. The
@XmlType
annotation on classOrderContext
references the factory class. The unmarshaller will use the identified factory method in this class.public class OrderFormsFactory { public OrderContext newOrderInstance() { return new OrderContext() } public PurchaseOrderType newPurchaseOrderType() { return new newPurchaseOrderType(); } } @XmlType(name="oContext", factoryClass="OrderFormsFactory", factoryMethod="newOrderInstance") public class OrderContext { public OrderContext(){ ..... } }In this example, a factory method is defined in a class, which also contains a standard class construct. Because the
factoryMethod
value is defined and nofactoryClass
is defined, the factory methodnewOrderInstance
is used during unmarshalling.@XmlType(name="oContext", factoryMethod="newOrderInstance") public class OrderContext { public OrderContext(){ ..... } public OrderContext newOrderInstance() { return new OrderContext(); } }Building and Running the j2s-xmlType Example Using NetBeans 5.5
Follow these instructions to build and run the
j2s-xmlType
example on your Application Server instance using the NetBeans 5.5 IDE.Building and Running the j2s-xmlType Example Using Ant
To compile and run the
j2s-xmlType
example using Ant, in a terminal window, go to the<INSTALL>
/javaeetutorial5/examples/jaxb/j2s-xmlType/
directory and type the following: