Is it possible to map an object to its corrisponding DTO when both belonging to a class hierarchy?
For example: I have a BaseEntity
and some ExtendedEntity1
.. ExtendedEntityN
On the other side I have a BaseDTO
and some ExtendedDTO1
.. ExtendedDTON
Then I have a service method:
public BaseDTO getById(String id) {
return orikaMapper.map(repository.findOne(id), BaseDTO.class);
}
This way I'am obviously getting always a BaseDTO
, but I'd like to map the entity to the right DTO type...
Is there a way to achieve this? I wouldn't to use switch
or instanceof
-check workarounds...
Not yet discovered a better solution (if one exists), so I'll go this way:
Map<Class<? extends BaseEntity>, Class<? extends BaseDTO>> dtoMappings;
I'm defining a mappings Map
where I put all the associations between entities and DTOs. Then in my method:
public BaseDTO getById(String id) {
BaseEntity e = repository.findOne(id);
return orikaMapper.map(repository.findOne(id), dtoMappings.get(e.getClass()));
}