简体   繁体   中英

Mapping a hierarchy of entities to a hierarchy of DTOs using Orika

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()));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM