1

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?

Florent06
  • 1,008
  • 2
  • 10
  • 29

2 Answers2

5

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.

Community
  • 1
  • 1
Andrew Nepogoda
  • 1,825
  • 17
  • 24
2

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

Mahendra Kapadne
  • 426
  • 1
  • 3
  • 10
  • This is not what I want. If you take a look at my objects, you'll see 2 DTOs and 2 entities. One of the entities has a field of type of the second. – Florent06 Dec 26 '17 at 10:11
  • What you are saying is also possible with MapStruct see this stack overflow link https://stackoverflow.com/questions/34130599/mapstruct-mapping-2-objects-to-a-3rd-one – Mahendra Kapadne Dec 26 '17 at 10:23
  • Thank you but I think this solution is a bit too hard to set up. Though, I can not set up it with my Junit Tests. – Florent06 Dec 27 '17 at 09:12