r/SpringBoot • u/[deleted] • Mar 03 '25
Discussion Using DTO in Spring Boot
Hi everyone, I am currently learning Spring Boot by creating a CRUD project and need some guidance.
I have created two DTOs—one for requests (RequestDTO) and another for responses (ResponseDTO).
For example, in a GET request by ID, I pass the ID in the URL, then store it in a RequestDtO id in controller layer and then send it to the service layer.
My doubt is about POST and PUT requests. When sending a full JSON request body, should I first store the request data in a DTO (RequestDTO) in controller layer and then pass it to the service layer? Or should I send the JSON directly to the service layer and convert it into an entity there before saving it in the repository?
Just wanted to let us know what is the standard approach in these s scenario.
3
u/bigkahuna1uk Mar 04 '25
No. The domain ideally should be kept pure of external influences and able to exist independently of any transport choices.
Say if instead of REST and JSON I wanted to change to using a binary protocol or a transport with different semantics like Kafka. That should have no bearing on the internal domain because it only deals with its own types. I can switch out a new protocol or transport because that happens at the adapter level.
These are design considerations though so it’s a subjective point of view. By using DTOs across controllers and services you’re introducing tight coupling between those components. That may be a trade off you’re willing to accept at the cost of flexibility. But using a hexagonal architecture for simple CRUD apps could also be considered overkill. So it’s a balancing act.
https://medium.com/booking-com-development/hexagonal-architecture-a-practical-guide-5bc6d5a6a056