Generating your model from a schema definition using Maven and JAXB

Categories Development, Java

If your project requires quite a large data model and it so happens that you have a xml schema definition on hand, you can easily transform that XSD into Java classes using Maven 2, JAXB and some manual labor.

Things you might want to know:
* doesn’t work out of the box on JSE6. It actually needs a lot of work, so avoid using for now;
* you need a maven project
* you actually need a valid XSD 🙂

The classes are generated by JAXB xjc. You can do this by hand, but using maven and maven-jaxb2-plugin makes it a breeze.

So, this is what you must do:
* Place your schema definition in your src/main/resources directory
* Open you pom.xml and add the following(no worries, you will remove them later):


<repositories>
<repository>
<id>maven2-repository.dev.java.net</id>
<name>Java.net Maven 2 Repository</name>
<url>http://download.java.net/maven/2</url>
</repository>
<repository>
<id>maven-repository.dev.java.net</id>
<name>Java.net Maven 1 Repository (legacy)</name>
<url>http://download.java.net/maven/1</url>
<layout>legacy</layout>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>maven2-repository.dev.java.net</id>
<name>Java.net Maven 2 Repository</name>
<url>http://download.java.net/maven/2</url>
</pluginRepository>
<pluginRepository>
<id>maven-repository.dev.java.net</id>
<name>Java.net Maven 1 Repository (legacy)</name>
<url>http://download.java.net/maven/1</url>
<layout>legacy</layout>
</pluginRepository>
</pluginRepositories>
<dependencies>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.0</version>
</dependency>
</dependencies>

* In your build section configure the jaxb2 plugin:

<plugin>
<groupid>org.jvnet.jaxb2.maven2</groupid>
<artifactid>maven-jaxb2-plugin</artifactid>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<includeschema>**/*.xsd</includeschema>
<generatepackage>com.gridpulse.project.model</generatepackage>
</configuration>
</plugin>

As you can see, you have 2 configuration settings:
* includeSchema – schema file mask to include
* generatePackage – the package that you would like to hold the classes

After setting this up, just fire up a mvn install. This will produce the model classes in the target/generated-sources/xjc/ directory.
You can now copy them to your src directory and clean them up.
Remember to remove the JAXB2 settings from your pom.

Leave a Reply

Your email address will not be published. Required fields are marked *