5
If possible, let’s imagine a context where Spring Boot and JPA are used.
During the construction of some REST API, I always wonder if I should perform the standard model request/Response. For example, consider the following scenario.
Our ultimate goal is to have an API that performs scheduling registration, where a scheduling can without abstracting as the following class in Java:
public class Agendamento {
private Autor autor;
private String texto;
}
Assuming that each schedule necessarily has an author, using Hibernate, our Entity class would look something like:
@Entity
public class AgendamentoEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
private Autor autor;
private String texto;
}
Thus, for the registration of a schedule, the required fields could be only the texto and the id of the author. Leading us to something like:
public class AgendamentoModelRequest {
private Long idAutor;
private String texto;
}
Thus, the agendamentoController would receive an object of the class AgendamentoModelRequest, which in turn would be using for a AgendamentoService, making use of a AgendamentoRepository to make the registration.
But in this case Agendamento is much like AgendamentoEntity (differs by the lack of id), as it will also be equal to AgendamentoModelReponse. Thus, we could "overload" the POJO scheduling into the context of model request/Sponse and Entity.
Is doing this necessarily a bad practice? Because that would make it a lot easier, since the context is about Agendamento, then the AgendamentoController could receive the POJO Agendamento (annotated with javax.validation/persistence Annotations and fasterxml.jackson.Annotation) and using it to be the API’s own return.