在mapstruct中@Mapping(target = "field", source = "")是什么意思?

rul*_*lo4 1 java mapping spring mapstruct

我刚刚克隆了一个带有一些映射结构映射器的存储库(1.3.1.Final),由于以下原因,构建失败:

java: No property named "" exists in source parameter(s). Did you mean "sourceField1"?

我将 mapstruct 更新为 version 1.4.2.Final,但结果相同。

查看代码,我发现我们有以下情况:

  • SourceClass与字段sourceField1, sourceField2,sourceField3
  • TargetClass与字段targetField1, targetField2,notInSourceField
    @Mapper(componentModel = "spring")
    public interface TheMapper {

        @Mapping(target = "targetField1", source = "sourceField1")
        @Mapping(target = "targetField2", source = "sourceField2")
        @Mapping(target = "notInSourceField", source = "")
        TargetClass mapToTarget(SourceClass source);
    }
Run Code Online (Sandbox Code Playgroud)

为了解决上述错误,我将行更改source = ""为:

@Mapping(target = "notInSourceField", expression = "java(\"\")") //means that notInSourceField = ""

但我假设这source = ""意味着该值将为空。这个假设正确吗?或者它实际上意味着什么?

Ben*_*eld 5

信息

为什么源注释中的默认值是“”?

使用默认值的原因是注释处理器知道用户定义的值和默认值source之间的区别。使用默认值时,它将使用而不是除非定义了,或之一。""""targetsourceconstantexpressionignore=true

@Mapping(target = "date", dateFormat = "dd-MM-yyyy")
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,该source属性也被命名为,但为了在和date之间进行转换,需要附加信息。在这种情况下,一个. 在这种情况下您不需要指定。sourcetargetdateFormatsource

来源

当源类中的属性名称与目标类中的属性名称不同时,您可以使用此方法。

@Mapping( target="targetProperty", source="sourceProperty" )
Run Code Online (Sandbox Code Playgroud)

持续的

当您想要应用常量值时,可以使用此选项。当字段应始终获得特定值时。

@Mapping( target="targetProperty", constant="always this value" )
Run Code Online (Sandbox Code Playgroud)

表达

这是当 mapstruct 没有其他功能可用于解决您的问题时使用的方法。在这里您可以定义自己的代码来设置属性值。

@Mapping( target="targetProperty", expression="java(combineMultipleFields(source.getField1(), source.getField2()))" )
Run Code Online (Sandbox Code Playgroud)

忽略

当您希望 mapstruct 忽略该字段时使用此方法。

@Mapping( target="targetProperty", ignore=true )
Run Code Online (Sandbox Code Playgroud)

回答

通过以上信息,我们现在知道您告诉 MapStruct 您要将属性设置notInSourceField为 property 。MapStruct 找不到名为 的方法get(),因此它告诉您该属性 不存在。您的情况的解决方案将如Yan 在评论中提到的那样使用constant=""而不是source="".

您可以在此处找到有关默认值和常量的更多信息。