2

ModelMapper で次のことをどのように表現できますか: ターゲットのフィールドに入力するには、ソースが null でない場合はソースのプロパティ A を使用し、それ以外の場合はプロパティ B を使用します。

例 (技術的な説明が気に入らない場合は、以下のコード): ModelMapper を使用して、ソース クラスSourceBigThingからターゲット クラスに変換したいとします。TargetSourceBigThingは 2 つのプロパティがあり、1 つは と呼ばれ、もう 1 つはredと呼ばれgreenます。これら 2 つのプロパティは、タイプが異なりRedSmallThingますGreenSmallThing。これらは両方とも と呼ばれるプロパティを持っていますnameSourceBigThingは赤または緑のいずれかを持つことができますが、両方を持つことはできません (もう一方は null です) 。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; 
}

条件をいじってみましたが、同じターゲットに対して 2 つのマッピングを行うことはできません。これは、ModelMapper がマッピングの重複に対して例外をスローするためです。

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

このgist で失敗した TestNG-Unit-Test を見つけることができます。

4

1 に答える 1

1

これは少し特殊なケースなので、これをうまく行う方法はありません。ただし、いつでも Converter を使用できます-次のようなもの:

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);
于 2014-09-10T17:34:38.630 に答える