views:

289

answers:

2

If a method of a JAX-RS application would return a domain object, the representation (say JSON) would contain all attributes of this object - right? But what if this object would contain "private" data, that shouldn't be exposed to the web?

And what is about the other direction from outside in: how could be prevented that private fields are overridden?

The only solution to this seems to create data transfer objects (dto).

To use an "automapper" wouldn't be the solution unless one can not specify what fields to map.

So, forces JAX-RS the developer to create DTOs? Or is there another solution?

+1  A: 

@XmlTransient (or a corresponding annotation) instructs the mappers/marshallers not to include the annotated property in the serialized output.

Bozho
Thanks, that is what I was looking for.
deamon
+2  A: 

For transparent marshalling and unmarshalling to and from XML of your entity, annotate it with JAXB annotations (a class can be annotated with both JPA and JAXB annotations and, this way, give an XML representation as well as be persisted in a database).

@Entity
@XmlRootElement
public class MyEntity implements Serializable {

    @Id @GeneratedValue
    private Long id;

    ....

}

In the above example I use only one JAXB annotation @XmlRootElement. Now, let's say that you don't want the id property in the serialized XML. Simply add the JAXB annotation @XmlTransient to it:

@Entity
@XmlRootElement
public class MyEntity implements Serializable {

    @XmlTransient
    @Id @GeneratedValue
    private Long id;

    ....

}

So, no, there is no strict need for DTOs (and the boilerplate code to map them to and from entities).

Pascal Thivent
Whow! Really cool!
deamon
Does @XmlTransient work with every output format JAX-RS supports or is it limited to XML and JSON?
deamon
@XmlTransient is from JAXB, JAXB is for XML. JSON outputters happen to support a subset. So it depends on serializer used for format in question. FWIW, I don't know of other 'standard' serializers, so it may be a moot point.
StaxMan