Guide to JAXB

1. Introduction

This is an introductory article on JAXB (Java Architecture for XML Binding).

First, we’ll show how to convert Java objects to XML and vice-versa, and then we’ll focus on generating Java classes from XML schema and vice-versa by using JAXB-2 Maven plugin.

2. Overview

JAXB provides a fast and convenient way to marshal (write) Java objects into XML and un-marshal (read) XML into objects. It supports a binding framework that maps XML elements and attributes to Java fields and properties using Java annotations.

The JAXB-2 Maven plugin delegates most of its work to either of the two JDK-supplied tools XJC and Schemagen.

3. JAXB Annotations

JAXB uses Java annotations for augmenting the generated classes with additional information. Adding such annotations to existing Java classes prepares them for the JAXB runtime.

Let’s first create a simple Java object to illustrate marshalling and un-marshalling:

@XmlRootElement(name = "book")
@XmlType(propOrder = { "id", "name", "date" })
public class Book {
    private Long id;
    private String name;
    private String author;
    private Date date;

    @XmlAttribute
    public void setId(Long id) {
        this.id = id;
    }

    @XmlElement(name = "title")
    public void setName(String name) {
        this.name = name;
    }

    @XmlTransient
    public void setAuthor(String author) {
        this.author = author;
    }

    // constructor, getters and setters
}

The above class above contains the following annotations:

  • @XmlRootElement: the name of the root XML element is derived from the class name and we can also specify the name of the root element of the XML using its name attribute

  • @XmlType: define the order in which the fields are written in the XML file

  • @XmlElement: define the actual XML element name which will be used

  • @XmlAttribute: define the id field is mapped as an attribute instead of an element

  • @XmlTransient: annotate fields that we don’t want to be included in XML

For more details on JAXB annotation, you may want to check out the following link.

4. Marshalling – Converting Java Object to XML

Marshalling provides a client application the ability to convert a JAXB derived Java object tree into XML data. By default, the Marshaller uses UTF-8 encoding when generating XML data. Next, we will generate XML files from Java objects.

Let’s create a simple program using the JAXBContext which provides an abstraction for managing the XML/Java binding information necessary to implement the JAXB binding framework operations:

public void marshal() throws JAXBException, IOException {
    Book book = new Book();
    book.setId(1L);
    book.setName("Book1");
    book.setAuthor("Author1");
    book.setDate(new Date());

    JAXBContext context = JAXBContext.newInstance(Book.class);
    Marshaller mar= context.createMarshaller();
    mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    mar.marshal(book, new File("./book.xml"));
}

The javax.xml.bind.JAXBContext class provides a client’s entry point to JAXB API. By default, JAXB does not format the XML document. This saves space and prevents that any white-space may accidentally be interpreted as significant.

To have JAXB format the output we simply set the Marshaller.JAXB_FORMATTED_OUTPUT property to true on the Marshaller. The marshal method uses an object and an output file where to store the generated XML as parameters.

When we run the code above, we may check the result in the book.xml to verify that we successfully convert Java object into XML data:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book id="1">
    <title>Book1</title>
    <date>2016-11-12T11:25:12.227+07:00</date>
</book>

5. Un-marshalling – Converting XML to Java Object

Un-marshalling provides a client application the ability to convert XML data into JAXB derived Java objects.

Let’s use JAXB Unmarshaller to un-marshal our book.xml back to a Java object:

public Book unmarshall() throws JAXBException, IOException {
    JAXBContext context = JAXBContext.newInstance(Book.class);
    return (Book) context.createUnmarshaller()
      .unmarshal(new FileReader("./book.xml"));
}

When we run the code above, we may check the console output to verify that we have successfully converted XML data into a Java object:

Book [id=1, name=Book1, author=null, date=Sat Nov 12 11:38:18 ICT 2016]

6. Complex Data Types

When handling complex data types that may not be directly available in JAXB, we may write an adapter to indicate JAXB how to manage a specific type.

Using JAXB’s XmlAdapter, we may define a custom code to convert an unmappable class into something that JAXB can handle. The @XmlJavaTypeAdapter annotation uses an adapter that extends the XmlAdapter class for custom marshaling.

Let’s create an adapter to specify a date format when marshaling:

public class DateAdapter extends XmlAdapter<String, Date> {

    private static final ThreadLocal<DateFormat> dateFormat
      = new ThreadLocal<DateFormat>() {

        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };

    @Override
    public Date unmarshal(String v) throws Exception {
        return dateFormat.get().parse(v);
    }

    @Override
    public String marshal(Date v) throws Exception {
        return dateFormat.get().format(v);
    }
}

We use a date format “yyyy-MM-dd HH:mm:ss” to convert Date to String when marshalling and ThreadLocal to make our DateFormat thread-safe.

Let’s apply the DateAdapter to our Book:

@XmlRootElement(name = "book")
@XmlType(propOrder = { "id", "name", "date" })
public class Book {
    private Long id;
    private String name;
    private String author;
    private Date date;

    @XmlAttribute
    public void setId(Long id) {
        this.id = id;
    }

    @XmlTransient
    public void setAuthor(String author) {
        this.author = author;
    }

    @XmlElement(name = "title")
    public void setName(String name) {
        this.name = name;
    }

    @XmlJavaTypeAdapter(DateAdapter.class)
    public void setDate(Date date) {
        this.date = date;
    }
}

When we run the code above, we may check the result in the book.xml to verify that we have successfully converted our Java object into XML using the new date format “yyyy-MM-dd HH:mm:ss“:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book id="1">
    <title>Book1</title>
    <date>2016-11-10 23:44:18</date>final
</book>

7. JAXB-2 Maven Plugin

This plugin uses the Java API for XML Binding (JAXB), version 2+, to generate Java classes from XML Schemas (and optionally binding files) or to create XML schema from an annotated Java class.

Note that there are two fundamental approaches to building web services, Contract Last and Contract First. For more details on these approaches, you may want to check out the following link.

7.1. Generating a Java Class from XSD

The JAXB-2 Maven plugin uses the JDK-supplied tool XJC, a JAXB Binding compiler tool that generates Java classes from XSD (XML Schema Definition).

Let’s create a simple user.xsd file and use the JAXB-2 Maven plugin to generate Java classes from this XSD schema:

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
    targetNamespace="/jaxb/gen"
    xmlns:userns="/jaxb/gen"
    elementFormDefault="qualified">

    <element name="userRequest" type="userns:UserRequest"></element>
    <element name="userResponse" type="userns:UserResponse"></element>

    <complexType name="UserRequest">
        <sequence>
            <element name="id" type="int" />
            <element name="name" type="string" />
        </sequence>
    </complexType>

    <complexType name="UserResponse">
        <sequence>
            <element name="id" type="int" />
            <element name="name" type="string" />
            <element name="gender" type="string" />
            <element name="created" type="dateTime" />
        </sequence>
    </complexType>
</schema>

Let’s configure the JAXB-2 Maven plugin:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>jaxb2-maven-plugin</artifactId>
    <version>2.3</version>
    <executions>
        <execution>
            <id>xjc</id>
            <goals>
                <goal>xjc</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <xjbSources>
            <xjbSource>src/main/resources/global.xjb</xjbSource>
        </xjbSources>
        <sources>
            <source>src/main/resources/user.xsd</source>
        </sources>
        <outputDirectory>${basedir}/src/main/java</outputDirectory>
        <clearOutputDir>false</clearOutputDir>
    </configuration>
</plugin>

By default, this plugin locates XSD files in src/main/xsd. We may configure XSD lookup by modifying the configuration section of this plugin in the pom.xml accordingly.

By default, these Java Classes are generated in the target/generated-resources/jaxb folder. We may change the output directory by adding an outputDirectory element to the plugin configuration. We may also add a clearOutputDir element with a value of false to prevent the files in this directory from being erased.

We may also configure a global JAXB binding which overrides the default binding rules:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<jaxb:bindings version="2.0" xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
    xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    jaxb:extensionBindingPrefixes="xjc">

    <jaxb:globalBindings>
        <xjc:simple />
        <xjc:serializable uid="-1" />
        <jaxb:javaType name="java.util.Calendar" xmlType="xs:dateTime"
            parse="javax.xml.bind.DatatypeConverter.parseDateTime"
            print="javax.xml.bind.DatatypeConverter.printDateTime" />
    </jaxb:globalBindings>
</jaxb:bindings>

The global.xjb above overrides the dateTime type to the java.util.Calendar type.
When we build the project, it generates class files in the src/main/java folder and package com.baeldung.jaxb.gen.

7.2. Generating XSD Schema from Java

The same plugin uses the JDK-supplied tool Schemagen. This is a JAXB Binding compiler tool that can generate an XSD schema from Java classes. In order for a Java Class to be eligible for an XSD schema candidate, the class must be annotated with a @XmlType annotation.

We reuse the Java class files from the previous example. Let’s configure the plugin:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>jaxb2-maven-plugin</artifactId>
    <version>2.3</version>
    <executions>
        <execution>
            <id>schemagen</id>
            <goals>
                <goal>schemagen</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <sources>
            <source>src/main/java/com/baeldung/jaxb/gen</source>
        </sources>
        <outputDirectory>src/main/resources</outputDirectory>
        <clearOutputDir>false</clearOutputDir>
        <transformSchemas>
            <transformSchema>
                <uri>/jaxb/gen</uri>
                <toPrefix>user</toPrefix>
                <toFile>user-gen.xsd</toFile>
            </transformSchema>
        </transformSchemas>
    </configuration>
</plugin>

By default, JAXB scans all the folders under src/main/java recursively for annotated JAXB classes. We may specify a different source folder for our JAXB annotated classes by adding a source element to the plug-in configuration.

We may also register a transformSchemas, a post processor responsible for naming the XSD schema. It works by matching the namespace with the namespace of the @XmlType of your Java Class.

When we build the project, it generates a user-gen.xsd file in the src/main/resources directory.

8. Conclusion

In this article, we covered introductory concepts on JAXB. For details, we can take a look at the JAXB home page.

We can find the source code for this article on GitHub.

Leave a Reply

Your email address will not be published.