a3dsfcv
a3dsfcv

Reputation: 1274

Spring MVC create object request

I'm writing service with spring MVC to add books to library. So I have a method @PostMapping(...) public Book addBook(@RequestBody Book book) {...} but the thing is Book object contains lots of fieds, but I want only some of them to allow to be passed to addBook request. Lets say in a book there is a field lastRequestedTime, and I never want allow user to fill this parameter.

My idea is to create new class AddBookRequest with all required fields, so my method will look like this: @PostMapping(...) public Book addBook(@RequestBody AddBookRequest book) {...} but in this case I will need to make lots of **Requst classes almost for every request.

How much am I right? Are there any better approaches?

Upvotes: 0

Views: 493

Answers (1)

jolice
jolice

Reputation: 98

Your idea is right, what you're going to implement is DTO pattern.

The idea is to decouple your request bodies from your domain model (assuming the Book is a business entity). They refer to distinct application layers: controller and domain model respectively.

Such a distinction has many advantages:

  • Changes to the request logic don't affect business entities (and vice-versa)
  • Request objects don't contain extra fields (that's your case)
  • Serialization logic is not mixed with the domain model definition (for example, you may want to put some Jackson annotations on the properties of your request object)

However, note that there's one significant disadvantage: code duplication.

Upvotes: 1

Related Questions