RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Generate an XML Document from an Object Model with JAXB 2 : Page 5

Learn how to get an XML document from your Java object model using JAXB 2. With annotations, you can also customize the document and use adapters to format data.

Annotations for Persistence
Some of you might already know of the fictional music company called Watermelon. I've used it in two previous articles about JPA ("Master the New Persistence Paradigm with JPA" and "Persistence Pays Offs: Advanced Mapping with JPA"). If you think of JAXB as a way to persist data into XML, JPA is its counterpart in terms of relational databases. In fact, both technologies rely heavily on annotations. That means that the same class can be annotated by JPA and JAXB annotations and, in this way, can give an XML representation as well as be persisted in a database.

For those of you interested in this double use of annotations, you will find an example in the code download. But just to give you a taste, here is what the Address class would look like:

@Table(name = "t_address")
@XmlType(propOrder = {"street", "zipcode", "city", "country"})
public class Address {

  @Id @GeneratedValue
  private Long id;

  private String street;

  @Column(length = 100)
  private String city;

  @Column(name = "zip_code", length = 10)
  @XmlElement(name = "zip")
  private String zipcode;

  @Column(length = 50)
  private String country;

  @ManyToMany(cascade = CascadeType.PERSIST)
  @JoinTable(name = "t_address_tag",
    joinColumns = {@JoinColumn(name = "address_fk")},
    inverseJoinColumns = {@JoinColumn(name = "tag_fk")})
  private List<Tag> tags = new ArrayList<Tag>();

  // Constructors, getters, setters

Antonio Goncalves is a senior architect specialized in Java/J2EE. Former BEA consultant he now helps insurance, finance and telecommunication clients set up their architectures. He also teaches J2EE at CNAM University in Paris.
Email AuthorEmail Author
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date