I just cloned a repo with some mapstruct mappers (1.3.1.Final
)
The build is failing due to following reason:
java: No property named "" exists in source parameter(s). Did you mean "sourceField1"?
I updated mapstruct to version 1.4.2.Final
, but with the same result.
Reviewing the code, I see we have the following situation:
SourceClass
with fieldssourceField1
,sourceField2
,sourceField3
TargetClass
with fieldstargetField1
,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);
}
To solve the error above, I changed the line with source = ""
to:
@Mapping(target = "notInSourceField", expression = "java(\"\")") //means that notInSourceField = ""
But I made this assuming that source = ""
means that the value will be empty. Is this assumption correct, or what actually does it mean?
CodePudding user response:
Information
Why is the default value in the annotation "" for source?
The reason for the default value for source
is that the annotation processor knows the difference between user defined ""
and the default value ""
. With the default value it will use target
instead of the source
unless one of constant
, expression
or ignore=true
is defined.
@Mapping(target = "date", dateFormat = "dd-MM-yyyy")
In the above example, the source
property is also named date
, but for the conversion between source
and target
additional information is needed. In this case a dateFormat
. You do not need to specify source
in this case.
source
This is what you use when the name of the property in the source class is different from the one in the target class.
@Mapping( target="targetProperty", source="sourceProperty" )
constant
This is used when you want a constant value applied. When a field should always get a specific value.
@Mapping( target="targetProperty", constant="always this value" )
expression
This is what is used when no other functionality of mapstruct is usable to solve your problem. Here you can defined your own code to set the property value.
@Mapping( target="targetProperty", expression="java(combineMultipleFields(source.getField1(), source.getField2()))" )
ignore
This is what is used when you want mapstruct to ignore the field.
@Mapping( target="targetProperty", ignore=true )
Answer
With the above information we now know that you tell MapStruct that you want to set the property notInSourceField
to the property
. MapStruct does not find a method called get()
, so it tells you that the property
does not exist.
The solution in your case would be as Yan mentioned in the comments to use constant=""
instead of source=""
.
You can find more information about default values and constants here.