wolfhunter
wolfhunter

Reputation: 33

Dto - Entity mapping best practice

I've been reading a bit about the DTO pattern lately. I understand its purpose; isolating internals and creating contracts for the client. However, I've been thinking a lot about how to map them to entities, efficiently.

So, let's say I have 2 Dtos; CreatePostDto and ReadPostDto which may vary in several fields. Now, I want to map them to a PostEntity, which can be done using technologies like modelmapper, mapstruct, etc. However, mapping them in the service layer doesn't seem very appealing to me as the code tends to get messy.

One way is creating a generic mapper abstract class and provide implementations for specific dtos. Nevertheless, I'm sceptical of this approach as I may have many dtos i.e many postDtos and this results to many mapper classes.

Is there a better way to do this?

Upvotes: 2

Views: 2031

Answers (2)

Karkala Srikanth
Karkala Srikanth

Reputation: 85

I know it is very old thread. I want to add my approach here, Why cant use ModelMapper directly without custom implementation for each single DTO to Entity mapping. ModelMapper modelMapper = new ModelMapper(); modelMapper.map(SourceObjectInstance, TargetObject.class);

if we need any special mapping for specific pair still can be configured in ModelMapper.

More Details:: https://modelmapper.org/user-manual/

Upvotes: 0

marc-gil
marc-gil

Reputation: 51

As you mentioned if you use Mapstruct you can build just one mapper class for each Entity. Mapstruct will implement the boilerplate code for you and you can have all the related mappings grouped. For example:

    public interface PostMapper {
    
        public PostEntity createPostDtoToPostEntity(CreatePostDto dto);
        
        public PostEntity readPostDtoToPostEntity(ReadPostDto dto);

    }

Even if your Post DTOs keep growing you can still group them in this mapper class.

Upvotes: 1

Related Questions