'How to use inheritance with ModelMapper's PropertyMap
I have been using the ModelMapper to convert Identity objects (entities) with DTO objects. I want to implement generic property conversions in a generic class for all entities (GenericEToDtoPropertyMap) and explicit property conversions in separate child-classes for each entity (PersonEToDTOPropertyMap for entity Person). To make it more clear, this is my code:
Generic property map:
public class GenericEToDtoPropertyMap<E extends Identity, DTO extends PersistentObjectDTO> extends PropertyMap<E, DTO> {
@Override
protected void configure() {
// E.oid to DTO.id conversion
map().setId(source.getOid());
}
}
Specific property map for entity Person:
public class PersonEToDTOPropertyMap extends GenericEToDtoPropertyMap<Person, PersonDTO> {
@Override
protected void configure() {
super.configure();
// implement explicit conversions here
}
}
Usage of property map:
modelMapper = new ModelMapper();
Configuration configuration = modelMapper.getConfiguration();
configuration.setMatchingStrategy(MatchingStrategies.STRICT);
modelMapper.addMappings(new PersonEToDTOPropertyMap());
// convert person object
PersonDTO personDto = modelMapper.map(person);
The problem is that the generic conversions do not apply. In my case person.oid does not get copied to personDto.id. It works correctly only if I remove the part:
map().setId(source.getOid());
from the GenericEToDtoPropertyMap.configure() method and put it in the PersonEToDTOPropertyMap.configure() method.
I guess, it has something to do with ModelMapper using Reflection to implement the mappings, but it would be nice if I could use inheritance in my property maps. Do you have any idea how to do this?
Solution 1:[1]
Well after 5 years... I got a solution (I have same problem)
After view some post and search answers I found this post The problem happen because the method "configure()" restricts what you can do inside so I thinking in create an method outside for get the custom format, so this is my code:
public class UserMap extends PropertyMap<User,UserLoginDTO> {
@Override
protected void configure() {
using(generateFullname()).
map(source,destination.getFullName());
}
private Converter<User, String> generateFullname(){
return context -> {
User user = context.getSource();
return user.getName()+ " " + user.getFirstLastname() + " " + user.getSecondLastname();
};
}
}
so you could call it from your main method or wherever you need, like this:
ModelMapper modelMapper=new ModelMapper();
modelMapper.addMappings(new UserMap());
and the output is:
UserLoginDTO{id='001', fullName='Jhon Sunderland Rex'}
How you can see, the logic is out of configure method and it works, I hope this helps for others
pd: sorry for my english
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
