Mapstruct:嵌套对象的自定义映射方法

时间:2020-11-02 15:36:20

标签: java nested mapping mapstruct

我想使用mapstruct在这些对象之间进行映射:

MyObj1
-List<MyObj2> myObj2List
--List<MyObj3> myObj3List
---string field1

MyObj4
-List<MyObj5> myObj5List
--List<MyObj6> myObj6List
---int field1

问题:我可以以某种方式告诉mapstruct将string1的field1映射到int而不是默认的Integer.parseInt(...)吗?

不能更改内部对象的类型。 我知道有一个注释

 @Mapping(source = "myObj2List.myObj3List.field1", target = "myObj5List.myObj6List.field1", qualifiedByName = "methodToMapWith")
 public MyObj4 field1Mapper(MyObj1input);
    
 @Named("methodToMapWith") 
 public static int methodToMapWith(string input) { 
    return ...[custom logic]...; 
 }

但是由于这些是嵌套对象,因此我收到一条错误消息,说No property named "myObj2List.myObj3List.field1" exists in source parameter(s).我必须将源格式错误。有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

您正在尝试定义集合上的映射。 MapStruct不支持此功能。

使用时

@Mapping(source = "myObj2List.myObj3List.field1", target = "myObj5List.myObj6List.field1", qualifiedByName = "methodToMapWith")

您实际上是在告诉MapStruct您要使用myObj3List中的属性myObj2List。但是,myObject2List不是bean,而是集合。

您实际上是要告诉MapStruct将映射传递到为单个元素创建的可迭代映射。

我认为有一个功能要求来支持类似的东西。

为了支持所需的功能,您需要在不同对象之间添加映射方法。

例如

 @Mapping(source = "myObj2List", target = "myObj5List")
 public MyObj4 field1Mapper(MyObj1 input);

 @Mapping(source = "myObj3List", target = "myObj6List")
 public MyObj5 map(MyObj2 input);

 @Mapping(target = "field1", qualifiedByName = "methodToMapWith")
 public MyObj6 map(MyObj3 input);
    
 @Named("methodToMapWith") 
 public static int methodToMapWith(string input) { 
    return ...[custom logic]...; 
 }

targetsource相同时,您不必定义它们,只需定义targetqualifiedByName