Reputation: 11
I'm planning on using CXF's rest implementation. I'm thinking of simply annotating my entity classes with jaxb annotations, such as @XmlRootElement
, in order to create response objects. The benefit being avoidance of code duplication. As for the (client) request object, which will be used by a separate web app, I'm thinking of 'copying' the entity classes, removing the orm annotations, and adding jaxb annotations.
Based on the above:
@XmlRootElement
, how can I stop the relational properties from being added (or considered apart of) to the response object?Upvotes: 1
Views: 2321
Reputation: 149047
Are there any dangers of creating request/response objects from entity classes?
Your request/response objects will need to be able to be mapped to XML. There are some pain points in mapping JPA entities to XML using standard JAXB APIs:
EclipseLink JAXB (MOXy) has specific extensions for mapping JPA entities to XML:
My entity classes contain relational properties, if I were to annotate them with @XmlRootElement, how can I stop the relational properties from being added (or considered apart of) to the response object?
You can use the JAXB @XmlTransient annotation to prevent a field from being converted to/fom XML.
Is there a better/easier way to create request objects rather than copying the entity classes, removing/adding annotations?
I would recomment using your entities directly. For an example see:
Upvotes: 0
Reputation: 14479
@javax.xml.bind.annotation.XmlTransient
will eliminate a field from the schema (JAXB will ignore it). You can also customize with @javax.xml.bind.annotation.XmlAccessorType
Per @bohzo's answer, you don't even need to copy your entities. But if you don't, you are potentially coupling your entity classes to the XML, which means whenever you refactor your entities you have to update all clients (since the generated schema will be different!) In my opinion, the XML schema for the response / request objects should be designed apart from any entities so that they can better server their purpose. That frees the entities to be refactored in the future and to concentrate on their purpose.
Upvotes: 0
Reputation: 597402
You can combine many annotations without any troubles. For example you can have:
@Column
@XmlElement
private String name;
Thus you can reuse the same class for all purposes, without the need to copy it.
The project you mentioned - hyperjaxb3 - does exactly that - it generates both JAXB and JPA annotations based on a schema.
Upvotes: 1