JAXB2 Tutorial

Learn JAXB2 in simple step-by-step way. This series of JAXB2 tutorial is based on JAXB version 2.

Java Architecture for XML Binding [JAXB] is one of the most popular API and industry standard to convert Java object into XML structures and vice versa. It’s used heavily in industries using web-services to communicate over the internet. It’s a standard API comes bundled with JDK(starting from JDK version 1.6). We will be using JAXB version 2. This series of post will help you to understand the JAXB basic and advanced usage including

  • Marshalling : Converting Java objects into XML documents.
  • UnMarshalling : Converting XML documents into Java objects.
  • Code Generation : Generating Java objects using a schema [XSD].
  • JAXB Annotations : Frequently used JAXB annotations.

JAXB2 Hands-on Examples

In this tutorial series, we will go through basic and advance usage of JAXB API, showing full working and downloadable example code.

JAXB2 Marshalling/UnMarshalling & basic usage Example
Simple JAXB HelloWorld java application explaining basic concepts like Marshalling and UnMarshalling, common JAXB Annotations , JAXBContext core API and setup.

JAXB2 Schema Validation Example
Example showing JAXB mapping validation against an XSD.

JAXB2 Code generation from XSD using Maven JAXB2 plugin
Example showing code generation from an XSD using maven-jaxb2-plugin and then using the generated code in our application.

JAXB2 Annotations Example
Example showing frequently used JAXB annotations in detail.

Before JAXB

Java being platform independent is the preferred way to develop portable object oriented applications. XML is the industry level standard to exchange information over internet. Thus Java and XML are often used together to develop flexible applications which provides seamless integration with other applications [web-services e.g.]

Before JAXB came into existence, the popular approach to use XML inside JAVA programs was to use some kind of parser(SAX or DOM), which parses input XML and populates the objects using callbacks written by you. The programs tends to be way too focused on manual parsing of XML document, expecting developer to be well-versed in XML know-hows, and a slight change in XML means you would be doing a major re-factoring to handle that.

The mirrored side(creating XML from Java) wasn’t a fun either. You had to prepare strings of XML looping through properties of java objects, handling manually the different kind of checks(a property is required/ optional, an element can appear inside a complex type, etc..).But happily, that was the past.

Enter JAXB. With Jaxb, we are no longer worried about XML parsing manually. By using just few annotations , you can convert your Java class into XML. Similarly you can generate your Java classes from XML or a XSD/schema using JAXB apis and plugins available. You can even validate your generated xml against a schema.