如何在Java 8和ModelMapper中使用Explicit Map?

问题描述:

我通过官方文档 http://modelmapper.org/getting-started/

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

有使用Java 8进行显式映射的代码示例

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);
});

如何正确使用此代码?当我在IDE中键入此代码段时,IDE向我显示消息cannot resolve method map

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

在此示例中,他们错过了一个步骤,他们使用的addMappings方法是addMappings/javadoc/org/modelmapper/TypeMap.html"rel =" noreferrer> TypeMap ,而不是ModelMapper中.您需要为2个对象定义一个TypeMap.这样:

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);
});

另一种方法是使用ModelMapper中的addMappings方法.它不使用lambda,并且使用 PropertyMap .它也足够短:

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());
  }
});