The Java Architecture for XML Binding (or JAXB) is an extremely useful library for converting from a Java POJO-style object model to XML and back. In fact it has become so popular that it is now included in the J2EE platform. In this introduction, I will focus mainly on getting your Java objects into an XML representation – but this is just scratching the surface when it comes to the features of JAXB.
The first step is creating a simple Maven quickstart project and adding the following dependencies to your POM file:
Let’s start with a basic example. Personally, I like to start with my Java object model and work my way down. Here are my objects (getters and setters are necessary but not shown).
Notice that only one JAXB annotation is used in my entire object model definition. All I need to do is specify the root element and JAXB will do the rest.
In order to see what XML is generated, just write a simple unit test:
The resulting XML will look something like this:
As you can see, JAXB is extremely simple to use and very quick to get started with. If you have a simple model, you only really need to know one annotation! This is a relief for those of us who have struggled with the dozens of tags in Spring and Hibernate. However, JAXB is also useful for more complex models, in which case an XML schema should be provided. I will discuss this further in the future.
Hello, I'm Arthur. I'm a software engineer.
Currently my focus is on test-driven software design and
development for scalable web services and web applications.
This site is largely dedicated, but not limited to, topics in this area.
Feel free to contact me using any of the links below.