Where to put Entity To DTO transformation in a Spring boot project?

The best way, based on your project structures. However, if you always call services into controller, you should use the Option 2 then it will return what the desired results.

Furthermore, if you want cut down lots of codes of the transformation in the method, you could create a converter class by using @Component to map your entity and DTO.


I believe better way of converting entity to DTO would be :

  • If you don't really need entity in service, then convert entity to
    DTO on repository level only. Also if you're using Spring Data JPA,
    then you can directly convert entity to DTO without any extra code.
    But if you're writing your complex queries which can not be fulfilled by it, then you can convert it inside your repo implementation.
    Doing this will ensure that no services will ever get hold of data
    which it must not have. No sensitive data will be exposed.

  • If you really need entity and there's no work around for it, then
    you can convert it to DTO in service layer as controller must never
    have data access which it should not. No sensitive data should ever
    be exposed to controller level. It's not a good design.

I think these are ways you can do conversion of entity to DTO, but the best design is to convert entity to DTO in repo itself.

I hope this helps you solve your problem.

Good luck!