I'm using JAXB(xjc version 2.2.4-2) to generate Java classes from a XML Schema. The XML types that map to a Java primitive datatype don't add:
@XmlElement(required = true)
For example when using:
<element name="userId" type="long"/>
<element name="userName" type="string"/>
will result in:
//no annotation added here
protected long userId;
@XmlElement(required = true)
protected String userName;
Does anyone have an explanation why this happens?
Does any of this have to do with options that you can set with xjc?
After the Java artifacts for your application are generated, you can generate fully annotated Java classes from an XML schema file by using the JAXB schema compiler, xjc command-line tool.
JAXB @XmlRootElement annotation type @XmlRootElement maps a class or an enum type to an XML element. When a top level class or an enum type is annotated with the @XmlRootElement annotation, then its value is represented as XML element in an XML document.
Java Architecture for XML Binding (JAXB) provides a fast and convenient way to bind XML schemas and Java representations, making it easy for Java developers to incorporate XML data and processing functions in Java applications.
You don't need an annotation to show that a property of Java type long
is required as this is implicit from the fact that primitive values can't be null. A non-nillable required element of type xs:long
maps to Java long
, an optional or nillable one maps to java.lang.Long
(which permits null
, representing absent or xsi:nil
as appropriate).
An element that is both optional and nillable (odd, but allowed by XML Schema) would map to a JAXBElement<Long>
to distinguish between absent (a null
JAXBElement
) and nil (a non-null JAXBElement
whose isNil()
returns true).
If you don't mind a BigInteger in your java class you could use type="integer" or type="positiveInteger" (negative userId?). Your validation will work this way at a certain cost.
Another option would be to use jaxb custom bindings. Your element could be:
<element name="userId" type="long"/>
and your have to create an extra binding file e.g.
<jxb:bindings version="1.0"
xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
jxb:extensionBindingPrefixes="xjc">
<jxb:bindings schemaLocation="my.xsd" node="//xs:element[@name='UserType']//xs:element[@name='userId']">
<jxb:property>
<jxb:baseType name="java.lang.Long" />
</jxb:property>
</jxb:bindings>
</jxb:bindings>
Now you can call xjc like: xjc my.xsd -b my.xjb
This results in:
@XmlElement(required = true, type = Long.class)
protected Integer userId;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With