将参数传递给自定义映射功能

时间:2019-07-25 14:43:42

标签: java mapstruct

使用MapStruct,并希望将常量/参数传递给自定义映射器

我的目的地的字段类型为Map<String, Restriction> restrictions。源可能有2-3个字符串字段,需要将其映射到映射中的单个“限制”。地图的关键只是一个常数。使用Map-struct Mapping批注,我想将此键传递到自定义映射器中,以便我可以在Map中创建初始值或在Map中检索现有值。

   @Mappings({

          @Mapping(source="source.someField", target="restrictions", constant="someKey"),

          @Mapping(source="source.startDate", target="restrictions", constant="someKey"),

          @Mapping(source="source.EndDate", target="restrictions", constant="someKey")

   })

   public abstract void restrictToClassA(SomeDataEntity source, @MappingTarget ClassA destination);

1 个答案:

答案 0 :(得分:0)

常量是替代目标的方法。您不能在同一@Mapping批注中同时指定两者。但是,从您的故事中我发现,您可以控制“ ClassA”目的地。因此,您可以将映射分为四组。所以:

Public Quadrupel{

   String prop1;
   String prop2;
   String prop3;
    //Getters/setters

}

ClassA{

   Quadrupel key1;
   Quadrupel key2;
    //Etc
    //Getters/setters

}

Into ClassA. Properties would then be along the lines of your key name. Your custom mapper could pick those up and map them in your target map. Although, the key would then a bit dubious as well since the property would indicate the same