Monday, March 09, 2009

Introduce JAXB to your POJOs

Suppose you want to keep your POJO really a POJO? If you use JPA annotations on a class, is it still really a POJO? A POJO should be usable as a domain object independent of whether it came from a database, or from a remote service. So If I see @Entity on your POJO, I know it is really a database object, and I start thinking all about it's dependencies, do I need a transaction, do I need a JDBC connection, what JAR has the JPA annotation, maybe it isn't in my JRE, no more a "plain" Java object.

Ok, but I want to store my POJO in a database, what do I do? Ok, that will be my next article... Today, what if I want to use JAXB to serialize the POJO as XML? Then I need to use @javax.xml.bind.annotation.XmlRootElement to annotate the class. That just ruined my POJO. AspectJ can add fields, methods, annotations, and parents to classes. Why not just introduce the JAXB annotations necessary to marshal the object at runtime just for the situation that I need?

Here is my POJO:
public class Order {
private String number;
private String product;
private String customerEmail;
private String customerName;
}


Now, here is the POJO with the JAXB annotation:
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Order {
private String number;
private String product;
private String customerEmail;
private String customerName;
}


Isn't marshaling an object to XML a totally different concern from if an Order needs the customer's email address? So, let's separate those two concerns:

import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public aspect Jaxbify {
declare @type : Order : @XmlRootElement;
}

This aspect introduces the XmlRootElement annotation to the Order class, keeping Orders, Orders.
Next time I'll show how to run this example.

No comments:

Labels