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

If the JAX-RS application method returns a domain object, the view (for example, JSON) will contain all the attributes of that object - right? But what if this object contains "private" data that should not be exposed to the Internet?

And what is another direction from the outside: how can you prevent the redefinition of private fields?

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

Using automapper will not be a solution unless you specify which fields to display.

So what makes a JAX-RS developer create a DTO? Or is there another solution?

+3
source share
3 answers

For transparent sorting and parsing with XML of your object, annotate it with JAXB annotations (a class can be annotated with JPA and JAXB annotations and thus provides an XML representation and is also stored in the 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 do not need a property idin serialized XML. Just add the JAXB annotation @XmlTransientto it:

@Entity
@XmlRootElement
public class MyEntity implements Serializable {

    @XmlTransient
    @Id @GeneratedValue
    private Long id;

    ....

}

So, no, there is no strict need for a DTO (and the template code for comparing them with entities).

+3
source

I think it’s better to say that JAX-RS requires you to use views .

My Foo , RESTful. Bar ( ) , . , , REST HTTP.

RESTful Foo/Bar , URI. , DTO, ( ) , , , , HATEOAS.

, . Foo → * Bar, Bar ? URI , , , .

GET foo/fff

<foo>
  <link rel="self" uri="uri="foo/fff" />
  <bar uri="bar/abc123">
    <status="Active" />
  </bar>
  <bar uri="bar/qqq">
    <status="Inactive" />
  </bar>
</foo>

,

GET bar/abc123

<bar>
  <link rel="self" uri="bar/abc123" />
  <foo uri="foo/fff" />
  <status>Active</status>
  <title>Some Bar</title>
  ...
</bar>
+2

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

+1
source

Source: https://habr.com/ru/post/1728295/


All Articles