如何在Java 8和ModelMapper中使用Explicit Map? [英] How to use Explicit Map with Java 8 and ModelMapper?

查看:135
本文介绍了如何在Java 8和ModelMapper中使用Explicit Map?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过官方文档 http://modelmapper.org/getting-started/<了解如何使用ModelMapper/a>

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

这篇关于如何在Java 8和ModelMapper中使用Explicit Map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆