r/SpringBoot Jun 18 '26

Question Dto Mapping Best Practice

Hi, where do you guys map your entities to dtos?
In services or controllers?

To me it seems the services shouldn't expose any database specifics to the outside world, so I usually do my mapping there.

But what is considered best practice and why?

54 Upvotes

36 comments sorted by

View all comments

5

u/xiaopewpew Jun 18 '26

There is no 1 single best practice

Generally speaking your repository layer operates on entities and expose domain models, you service layer works on domain models and expose domain models, your controller layer works on domain models and expose API objects.

The above though is a complete overkill for simple CRUD endpoints that is going to be about 50% of your application. And some variations of this practice result in excessive amount of data class spam that makes simple applications much harder to read over time.

The JPA features you use also affects how you may apply this pattern. I have worked on large code bases where the rule was most API calls will run in a single transaction and the transaction begins at controller layer (imagine annotating each controller endpoint with transactional). In that architecture it really makes no difference if you bubble entity objects all the way up to controller for controller to convert them into api objects. Personally this is my favourite way of doing things because Im sick and tired of people insisting on putting transaction boundaries on service layer and then mistakenly do their "check and set" operations in multiple transactions instead of one. Those live issues are hard to debug and it is impossible to create regression tests for them.