How to use Explicit Map with Java 8 and ModelMapper?

hudrogen picture hudrogen · Feb 27, 2018 · Viewed 16.8k times · Source

I learn how to use ModelMapper by official documentation http://modelmapper.org/getting-started/

There is code sample for explicit mapping using java 8

modelMapper.addMappings(mapper -> {
  mapper.map(src -> src.getBillingAddress().getStreet(),
      Destination::setBillingStreet);
  mapper.map(src -> src.getBillingAddress().getCity(),
      Destination::setBillingCity);
});

How to use this code correctly? When I type this code snippet in IDE, IDE show me message cannot resolve method map

enter image description here

Answer

Bentaye picture Bentaye · Feb 27, 2018

They missed a step in this example, the addMappings method they use is the addMappings from TypeMap, not from ModelMapper. You need to define a TypeMap for your 2 objects. This way:

// Create your mapper
ModelMapper modelMapper = new ModelMapper();

// Create a TypeMap for your mapping
TypeMap<Order, OrderDTO> typeMap = 
    modelMapper.createTypeMap(Order.class, OrderDTO.class);

// Define the mappings on the type map
typeMap.addMappings(mapper -> {
    mapper.map(src -> src.getBillingAddress().getStreet(), 
                      OrderDTO::setBillingStreet);
    mapper.map(src -> src.getBillingAddress().getCity(), 
                      OrderDTO::setBillingCity);
});

An other way would be to use the addMappings method from ModelMapper. It does not use lambdas and takes a PropertyMap. It is short enough too:

ModelMapper modelMapper = new ModelMapper();
modelMapper.addMappings(new PropertyMap<Order, OrderDTO>() {
  @Override
  protected void configure() {
    map().setBillingStreet(source.getBillingAddress().getStreet());
    map().setBillingCity(source.getBillingAddress().getCity());
  }
});