Mapping a hardcoded value with ModelMapper

Viewed 2129

I'm evaluating the ModelMapper library to map a project DTOs and Entities. Although the library is quite powerful, I could not find a way to map a hardcoded value from on Entity to its DTO representation.

The ModelMapper, maps a method from source class to a method on destination class. For example:

modelMapper.createTypeMap(MyEntity.class, MyDTO.class)
    .addMappings(mapper -> mapper.map(MyEntity::getName, MyDTO::setFirstName))
    .addMappings(mapper -> mapper.map(MyEntity::getSurname, MyDTO::setLastName))

But I've an attribute on DTO which is not present on the entity side yet. Using a Spring converter class, this mapping was always done by a hardcoded value like this dto.setStatus("ACTIVE");. But using ModelMapper I can't figure out how to do it properly. My first attempt was something like that:

    .addMappings(mapper -> mapper.map(s -> {return "ACTIVE";}, MyDTO::setStatus))

However, the mapping above does not work since ModelMapper expects to map a get method from the source. Thus, a return has no effect and in fact the code above results in runtime error.

A possible solution, which is quite ugly is to force the desired result with using helper like this:

addMappings(mapper -> mapper.using(c -> "ACTIVE").map(MyEntity::getName, MyDTO::setStatus)); 

In this case, the getName method is used just to provide a get method while the real value will be replaced by ACTIVE. But since this is a unclear solution, I would like to understand whether there is a better solution to solve this using ModelMapper.

Another solution is add to my entity/dto a method public String getStatus() { return "ACTIVE"; }. But I really would like to keep all hardcoded values on mappers.

0 Answers
Related