2014-09-10 69 views
2

如何在ModelMapper中表达以下内容:要在目标中填充字段,我想要使用源的属性A(如果它非空),否则使用属性B.如何在ModelMapper中将源映射到同一对象

示例(以下代码,如果您不喜欢技术说明): 假设我想使用ModelMapper从源类SourceBigThing到目标类TargetSourceBigThing有两个属性,一个叫red,另一个叫​​。这两个属性是不同类型的RedSmallThingGreenSmallThing。这两件事都有一个名为name的属性。 A SourceBigThing可以有红色或绿色,但不能同时有两个(其他为空)。我想将Small Things的名称映射到目标类的属性。

例码:

class SourceBigThing { 
    private final SourceSmallThingGreen green; 
    private final SourceSmallThingRed red; 
} 

class SourceSmallThingGreen { 
    private final String name; 
} 

class SourceSmallThingRed { 
    private final String name; 
} 



class Target { 
    private TargetColorThing thing; 
} 

class TargetColorThing { 
    // This property should either be "green.name" or "red.name" depending 
    // on if red or green are !=null 
    private String name; 
} 

我试着玩的条件语句,但你不能有两个映射到相同的目标,因为ModelMapper抛出的副本映射异常:

when(Conditions.isNotNull()).map(source.getGreen()).setThing(null); 
when(Conditions.isNotNull()).map(source.getRed()).setThing(null); 

你可以在this gist找到一个失败的TestNG-Unit-Test。

回答

1

这是一个不寻常的案例,所以没有完成这样做的方法。但你总是可以使用一个转换器 - 例如:

using(new Converter<SourceBigThing, TargetColorThing>(){ 
    public TargetColorThing convert(MappingContext<SourceBigThing, TargetColorThing> context) { 
    TargetColorThing target = new TargetColorThing(); 
    if (context.getSource().getGreen() != null) 
     target.setName(context.getSource().getGreen().getName()); 
    else if (context.getSource().getRed() != null) 
     target.setName(context.getSource().getRed().getName()); 
    return target; 
}}).map(source).setThing(null); 
相关问题