Reputation: 988
Here are my DTOs:
public class TagVolumeDTO {
private Long id;
private Long idTag;
//...
}
public class TagTDO {
private Long id;
private Long amount;
//...
}
and here are my entities:
public class TagVolume {
private Long id;
private Tag tag;
//...
}
public class Tag {
private Long id;
private Long amount;
//...
}
I would like to configure my ModelMapper to map Tag#id to TagVolumeDTO#idTag. Is that possible?
Upvotes: 1
Views: 13559
Reputation: 1895
Configuration:
ModelMapper mapper = new ModelMapper();
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
mapper.typeMap(TagVolume.class, TagVolumeDTO.class)
.addMappings(m -> m.map(src -> src.getTag().getId(), TagVolumeDTO::setIdTag));
Usage:
Tag tag = new Tag();
tag.setId(1L);
tag.setAmount(10L);
TagVolume tagVolume = new TagVolume();
tagVolume.setId(123L);
tagVolume.setTag(tag);
System.out.println(mapper.map(tagVolume.getTag(), TagDTO.class));
System.out.println(mapper.map(tagVolume, TagVolumeDTO.class));
Output:
TagDTO(id=1, amount=10)
TagVolumeDTO(id=123, idTag=1)
ModelMapper version: 1.1.0
P.s. You can to organize your code similar to my answer in another question.
Upvotes: 5
Reputation: 426
For these kind of mapping it is preferred to used AnnotationProcessor like mapStuct which reduces code.
It will generate code for Mapper
@Mapper
public interface SimpleSourceDestinationMapper {
TagVolumeDTO sourceToDestination(Tag source);
Tag destinationToSource(TagVolumeDTO destination);
}
usage of these mapper is as follow
private SimpleSourceDestinationMapper mapper
= Mappers.getMapper(SimpleSourceDestinationMapper.class);
TagVolumeDTO destination = mapper.sourceToDestination(tag);
Kindly find link for detailed implementation MapStuct
Upvotes: 2