Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

398
Visualizações
Should entity class be used as request body

Suppose I have to save an entity, in this case, Book. I have the next code:

@RestController
@RequestMapping("books")
public class BookController {
    
    @Inject
    BookRepository bookRepository;
    
    @PostMapping
    public Book saveBook(@RequestBody Book book) {
        return bookRepository.save(book);
    }
}

My entity Book is a persistence entity:

@Entity(name = "BOOK")
public class Book{

    @Id
    @Column(name = "book_id")
    private Integer id;

    @Column(name = "title")
    private String title;

    (get/sets...)
}

The question is: is a bad practice use my persistence entity in @RequestBody of the controller layer? Or should I create a book DTO and map it to my persistence class in a service layer? What is better and why?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You should create a DTO class and map it to persistence class. Refer this rule description for the same. Reason specified is

if a persistent object is used as an argument of a method annotated with @RequestMapping, it’s possible from a specially crafted user input, to change the content of unexpected fields into the database

Apart from this, using DTO we can omit some of the persistent object properties that we don't wish to be present/visible in presentation layer.

You can map DTO class to persistence entity in controller itself like below.

@RestController
@RequestMapping("books")
public class BookController {
    
    @Autowired
    BookRepository bookRepository;

    @Autowired
    ModelMapper modelMapper
    
    @PostMapping
    public Book saveBook(@RequestBody BookDTO modelBook) {
        Book book = this.modelMapper.map(modelBook, Book.class);
        return bookRepository.save(book);
    }
}

ModelMapper is a framework that does the DTO to Entity and vice versa mapping. Check ModelMapper website.

You may refer answer and comments for more information about the same.

over 4 years ago · Santiago Trujillo Relatório

0

Yes, it is a really bad idea.

An entity represents persistent data maintained in a database and encapsulates enterprise-wide business rules. On the other hand, DTO is a dumb object - it just holds properties and has getters and setters, but no other logic of any significance. DTOs are used only to transfer data from one subsystem of an application to another.

Imagine having a new requirement to add a new many to many relationship:

@Entity(name = "BOOK")
public class Book{

    @Id
    @Column(name = "book_id")
    private Integer id;

    @ManyToMany
    Set<Student> likes;

... 
} 

Such a change in database would also change the API.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda