如何在 Java 8 和 ModelMapper 中使用显式映射?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49003929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 10:13:58  来源:igfitidea点击:

How to use Explicit Map with Java 8 and ModelMapper?

javajava-8modelmapper

提问by hudrogen

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

我通过官方文档http://modelmapper.org/getting-started/学习如何使用 ModelMapper

There is code sample for explicit mapping using java 8

有使用 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

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

enter image description here

在此处输入图片说明

回答by Bentaye

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

他们在这个例子中遗漏了一个步骤,addMappings他们使用的方法是addMappingsfrom TypeMap,而不是 from ModelMapper。您需要TypeMap为 2 个对象定义一个。这条路:

// 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 addMappingsmethod from ModelMapper. It does not use lambdas and takes a PropertyMap. It is short enough too:

另一种方法是使用addMappings方法 from ModelMapper。它不使用 lambdas 并采用PropertyMap。它也足够短:

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