Displaying hardcoded value with ModelMapper
I am evaluating the ModelMapper library for mapping DTO projects and objects. Although the library is quite powerful, I haven't been able to find a way to map the hardcoded value from the Entity to its DTO representation.
ModelMapper maps a method from the source class to a method from the 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 have a DTO attribute that is not yet on the entity side. Using the Spring converter class, this mapping has always been done with hardcoded code like this dto.setStatus("ACTIVE");
. But with ModelMapper, I can't figure out how to do this correctly. My first attempt was something like this:
.addMappings(mapper -> mapper.map(s -> {return "ACTIVE";}, MyDTO::setStatus))
However, the above mapping does not work as ModelMapper expects to map a method get
from the source. So the return has no effect, and in fact the code above results in a runtime error.
A possible solution, which is rather ugly, is to force the desired output with a using
helper like this:
addMappings(mapper -> mapper.using(c -> "ACTIVE").map(MyEntity::getName, MyDTO::setStatus));
In this case, the method getName
is only used to provide the method get
, while the real value will be replaced with ACTIVE
. But since this is a fuzzy solution, I would like to understand if there is a better solution to solve this using ModelMapper .
Another solution is adding my / dto object to the method public String getStatus() { return "ACTIVE"; }
. But I really would like to keep all the hardcoded values ββon the mappers.
source to share
No one has answered this question yet
Check out similar questions: