我正在使用JAXB(xjc版本2.2.4-2)从XML Schema生成Java类。映射到Java原始数据类型的XML类型不会添加:
@XmlElement(required = true)
例如使用时:
<element name="userId" type="long"/>
<element name="userName" type="string"/>
将导致:
//no annotation added here
protected long userId;
@XmlElement(required = true)
protected String userName;
有没有人解释为什么会这样?
这是否与您可以使用xjc设置的选项有关?
答案 0 :(得分:7)
您不需要注释来显示Java类型long
的属性是必需的,因为这是因为原始值不能为空的事实。类型为xs:long
的非可填充必需元素映射到Java long
,可选或可填写的元素映射到java.lang.Long
(允许null
,表示缺席或xsi:nil
酌情)。
可选和 nillable(奇怪,但XML Schema允许)的元素将映射到JAXBElement<Long>
以区分缺席(a { {1}} null
)和nil(JAXBElement
返回true的非空JAXBElement
。
答案 1 :(得分:2)
如果您不介意java类中的BigInteger,可以使用type =“integer”或type =“positiveInteger”(负userId?)。您的验证将以一定的成本以这种方式工作。
另一种选择是使用jaxb自定义绑定。你的元素可能是:
<element name="userId" type="long"/>
并且你必须创建一个额外的绑定文件,例如
<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>
现在你可以调用xjc:xjc my.xsd -b my.xjb
这导致:
@XmlElement(required = true, type = Long.class)
protected Integer userId;