4

In order to write the minimum amount of code required, I'm trying to let ModelMapper generate its implicit mapping and only write explicit property mappings for those properties that it couldn't auto-map.

If I let ModelMapper generate an implicit mapping using:

modelMapper.createTypeMap(SourceType.class, DestType.class);

it complains about setSomeId having multiple possible mappings. I then tried to fix just that using:

modelMapper.addMappings(new PropertyMap<SourceType, DestType>() {
    protected void configure() {
        map().setSomeId(source.getProperty().getWeirdID());
    }
});

However, I found that ModelMapper still complains, because an exception is actually thrown on createTypeMap, so it doesn't have a chance to reach my custom mapping code.

If I invert both statements, I get an error:

java.lang.IllegalStateException: A TypeMap already exists for class SourceType and class DestType

If I leave out createTypeMap completely, ModelMapper complains about missing mappings for all other properties of the DestType (those who it was able to map automatically with createTypeMap).

I found no explicit clue in the Documentation whether mixing implicit with explicit mappings is supported and how it's done.

Can anyone help?

4

3 回答 3

1

而不是ModelMapper.createTypeMap尝试ModelMapper.addMappings(首先)。这仍然会创建(并返回) a TypeMap,但PropertyMap这样做时会考虑到您。

于 2014-12-20T02:51:12.907 回答
1

不知道这对你来说是否仍然是一个问题,我必须承认我是 ModelMapper 的新手。我一直在努力解决您遇到/遇到的同样问题。我似乎已经解决了。

    TypeMap<RateDTO, Rate> rateDTORateTypeMap = modelMapper.getTypeMap(RateDTO.class, Rate.class);
    if(rateDTORateTypeMap == null) {
        rateDTORateTypeMap = modelMapper.createTypeMap(RateDTO.class, Rate.class);
    }
    rateDTORateTypeMap.setProvider(request -> {
        RateDTO source = RateDTO.class.cast(request.getSource());
        CurrencyAndAmount price = new CurrencyAndAmount(source.getPrice().getCurrencyCode(), source.getPrice().getAmount());
        return new Rate(price, source.getPaymentDate(), source.getPaymentId());
    });

基本上我首先尝试获取已经存在的 TypeMap,否则我创建一个新的/修改的映射。

希望能帮助到你

于 2016-09-02T05:50:54.780 回答
1

假设我们要映射Source sourceDestination destination. 代替

Destination destination = modelMapper.map(source, Destination.class);

为了结合显式和隐式映射,我们需要implicitMappings()添加TypeMap

public Destination mapSourceToDestination(Source source) {
            TypeMap<Source, Destination> typeMap = modelMapper
                    .typeMap(Source.class, Destination.class)
                    .implicitMappings()
                    .addMappings(mapper -> {
                        mapper.map(source -> source.getPropetryOne().getSubPropetryOne(), Destination::setPropetryA);
                    });
            return typeMap.map(source);
        }
于 2020-04-16T21:59:19.943 回答