Reputation: 180
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?
Upvotes: 8
Views: 7139
Reputation: 536
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;
Upvotes: 2
Reputation: 122364
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).
Upvotes: 8