JAXB quickstart via maven2

Apache Maven

Image via Wikipedia

JAXB is a java framework to XML-Java transformations.

JAXB is 2.1 has a very simple API like castor and jibx And annotation driven transformers. Although those configurations can be written manually JAXB has a code generator to generate java files from XSD files. Here is sample JAXB tutorial using maven2:

1. extending project dependency

<!-- ....-->


2. Adding jaxb2-mojo-plugin

<packagename>com.example.myschema</packagename> <!-- The name of your generated source package -->


3. adding your XSD files under /src/main/xsd
sample file: model1.xsd

4. generate your java file from XSD

mvn jaxb2:xjc

sample java code:

@XmlType(name = "PurchaseOrderType", propOrder = {
public class PurchaseOrderType {

@XmlElement(required = true)
protected USAddress shipTo;
@XmlElement(required = true)
protected USAddress billTo;
protected String comment;
@XmlElement(required = true)
protected Items items;


@XmlType(name = "", propOrder = {
public static class Item {

@XmlElement(required = true)
protected String productName;
protected int quantity;
@XmlElement(name = "USPrice", required = true)
protected BigDecimal usPrice;
protected String comment;
protected XMLGregorianCalendar shipDate;
@XmlAttribute(required = true)
protected String partNum;

5. And test your code

public class JAXBTest extends TestCase {
public void testMarshall() throws JAXBException {
JAXBContext jc = JAXBContext.newInstance("com.example.myschema");
ObjectFactory factory = new ObjectFactory();
PurchaseOrderType type = factory.createPurchaseOrderType();
Items items = factory.createItems();
Items.Item o = factory.createItemsItem();
o.setComment("part comment");


JAXBElement<purchaseordertype> element = factory.createPurchaseOrder(type);
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(element, System.out);

and output is

<item partnum="test">
<comment>part comment</comment>

Additional references:

maven jaxb plugins
sun official jaxb reference

Reblog this post [with Zemanta]

  • Trackback are closed
  • Comments (6)
  1. Thanks, this really helped!

  2. Thank you, was very confused with various plugins available, till the time I found your blog.

    thanks again for sharing

    • gungus
    • June 2nd, 2009

    Hi, nicely presented.

    Could you please correct the “mvn jxb2:xjc” to “mvn jaxb2:xjc”.


    • Hai-Long Nguyen
    • July 19th, 2011

    Hi, would you know what needs to be done in the POM file to generate equals() methods for each of the generated objects?

    Solutions I’ve found are only for org.jvnet.jaxb2.maven2

    But I need to use what you have above:

Comment are closed.