patternjavaMinor
JAXB XJC code generation - adding @XmlRootElement and Joda DateTime
Viewed 0 times
jaxbandaddinggenerationxmlrootelementcodejodaxjcdatetime
Problem
Here's an interesting scenario that I encountered the other day. I did eventually reach a solution on my own. However, I'd welcome any comments and better approaches.
The requirements
I want to generate JAXB objects based on a collection of XSDs using XJC as part of a Maven build. I'll be using JAXB-RI 2.1 as the implementation.
In addition, I want to make sure that all objects implement a signature interface (e.g.
Finally, I want to be able to select certain objects to act as root elements so I'll need to selectively add
I can't make any changes to the XSDs.
The approach
Step 1 - Configuring the pom.xml
Configure Maven to use the XJC plugin as follows:
The use of a dedicated execution configuration is there to allow additional mutually exclusive XSDs to be built using a differe
The requirements
I want to generate JAXB objects based on a collection of XSDs using XJC as part of a Maven build. I'll be using JAXB-RI 2.1 as the implementation.
In addition, I want to make sure that all objects implement a signature interface (e.g.
MySignature) which has no methods. Also, I want to avoid using XmlGregorianCalendar and have Joda DataTime instead (with a suitable adapter that I'll provide called DateUtils with parse() and format() methods).Finally, I want to be able to select certain objects to act as root elements so I'll need to selectively add
@XmlRootElement to some objects, and I have suitable XPath expressions to locate them. I can't make any changes to the XSDs.
The approach
Step 1 - Configuring the pom.xml
Configure Maven to use the XJC plugin as follows:
org.jvnet.jaxb2.maven2
maven-jaxb2-plugin
0.7.4
generate-domain1
generate
false
domain1.xsd
domain1-bindings.xjb
true
org.example.domain1
${project.build.directory}/generated-sources/domain1
-Xannotate
org.jvnet.jaxb2_commons
jaxb2-basics
0.6.0
org.jvnet.jaxb2_commons
jaxb2-basics-annotate
0.6.0
The use of a dedicated execution configuration is there to allow additional mutually exclusive XSDs to be built using a differe
Solution
The `
-
Use this tag instead:
Source
tag generates a new org.w3._2001.xmlschema.AdapterN class for each new javaType definition. So a better approach would be:
- Create a class extending
XmlAdapter. In it you will have to override the both methods defined. So in example, the class could be org.example.DateUtilsAdapter`.-
Use this tag instead:
Source
Code Snippets
<xjc:javaType
name="org.joda.time.DateTime"
xmlType="xs:time"
adapter="org.example.DateUtilsAdapter" />Context
StackExchange Code Review Q#1877, answer score: 8
Revisions (0)
No revisions yet.