Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JAX-RS require data transfer objects (DTO)?

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?

like image 303
deamon Avatar asked Dec 03 '25 03:12

deamon


1 Answers

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).

like image 143
Pascal Thivent Avatar answered Dec 04 '25 15:12

Pascal Thivent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!