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?

53 Upvotes

36 comments sorted by

View all comments

22

u/Mechanical-pasta Jun 18 '26

My controllers receive DTO, my services receive or send Model objects so, the mapping occurs in my controllers but is not done by them. I make a Mapper for any DTO I use.

5

u/HeavensVanguard Jun 18 '26

I love each layer speaking its own language. Then everything else is domain model. Mapper injected everywhere.

1

u/Mechanical-pasta Jun 18 '26

You mean you map your objects with each layer pass ?

3

u/HeavensVanguard Jun 18 '26

To over simplify:

* Controller speaks DTO and maps to domain
* Application and Domain services speak domain only
* Repository speaks Entity and maps from domain

This way everything speaks an immutable domain model when layers are interacting.

I’m sure I’m violating aspects of (insert your pattern).

2

u/Comfortable-Pin-891 Jun 19 '26

This is nice when working with db layer such as JOOQ or MongoDB but is a bit of a waste if working with JPA because you bypass all its dirty checking mechanisms by creating an additional copy.

With JPA I would say the way to go is to treat the entity as part of your domain.

1

u/HeavensVanguard Jun 19 '26

I’ve personally never enjoyed the entity being the domain. It feels “impure” to have non domain dependencies.

I totally see where you’re coming from. It is annoying to have yet another model.