JAX-RS custom mapping from entities to xml
Here's my problem:
Say I have two entities annotated with JAX-RS开发者_开发技巧 annotations:
@XmlRootElement
@Entity
public Person {
private String firstname;
private String lastname;
private Address address;
}
@XmlType
@Entity
public Address {
private String street;
private String city;
}
This will get rendered into:
<person>
<firstname></firstname>
<lastname></lastname>
<address>
<street></street>
<city></city>
</address>
</person>
My question therefore is:
Is it possible to annotate those entities so that the xml returned is:
<person>
<firstname></firstname>
<lastname></lastname>
<street></street>
<city></city>
</person>
i.e. properties of Address entity are treated as Person properties (without the enclosing tags)?
You could do this using EclipseLink JAXB (MOXy). MOXy contains an annotation called @XmlPath, this is used to do XPath based mappings. The self XPath (".") will give you the desired effect:
@Entity
@XmlAccessorType(XmlAccessType.PROPERTY)
@XmlRootElement
public Person {
private String firstname;
private String lastname;
private Address address;
// getter and setter for firstname/lastname
@XmlPath(".")
public Address getAddress() { return address; }
public String getStreet() { return getAddress().getStreet(); }
// more getters and setters
}
For an example on using EclipseLink JAXB extensions see:
- http://bdoughan.blogspot.com/2010/07/xpath-based-mapping.html
- http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted/MOXyExtensions
In order to use MOXy as your JAXB implementation you must add a jaxb.properties file in with your model classes with the following content:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
BTW, MOXy also has a number of extensions for handling JPA entities:
- http://wiki.eclipse.org/EclipseLink/Examples/MOXy/JPA
I have posted a series of examples to my blog on how to create a JPA based RESTful service using JAX-RS:
- Part 1 - Data Model
- Part 2 - JPA
- Part 3 - JAXB (using MOXy)
- Part 4 - RESTful Service (using an EJB session bean)
I'm not entirely sure why you would want to, but this might work (untested)
@XmlRootElement
@Entity
@XmlAccessorType(XmlAccessType.PROPERTY)
public Person {
private String firstname;
private String lastname;
private Address address;
// getter and setter for firstname/lastname
@XmlTransient
public Address getAddress() { return address; }
public String getStreet() { return getAddress().getStreet(); }
// more getters and setters
}
@XmlType
@Entity
public Address {
private String street;
private String city;
// getters and setters
}
I personally would be using a DTO pattern at this point though. Mixing ORM and Serialization annotations is rarely a good thing.
精彩评论