Reputation: 1274
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
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:
However, note that there's one significant disadvantage: code duplication.
Upvotes: 1