I have been looking through the MapStruct documentation without any success.
I am implementing a mapping between my Domain classes and my DTO classes; using MapStruct. In my domain, I do not want to use Setters for my fields because, we know that today Setters are bad (for many reasons, but that's not the topic of my question).
However when I want to convert ItemDto into Item, I got the following message :
Error:(17, 21) java: Property "name" has no write accessor in my.example.Item.
However my class Item has a Business method void changeName(String newName) that I would like to use in my Mapper.
The code of my Mapper is :
@Mapper
public interface MyMapper {
@Mapping(source="nameDto", target = "name")
Item map(ItemDto dto);
}
My question is quite simple : how to specify StructMap to use changeName as write accessor ?
Thanks for your help.
In order to implement something like that you would have to write your own custom AccessorNamingStrategy.
If your domain objects follow the same pattern changeXXX then a simple implementation can look like:
public class CustomAccessorNamingStrategy extends DefaultAccessorNamingStrategy {
@Override
public boolean isSetterMethod(ExecutableElement method) {
String methodName = method.getSimpleName().toString();
return methodName.startsWith( "change" ) && methodName.length() > 6;
}
@Override
public String getPropertyName(ExecutableElement getterOrSetterMethod) {
String methodName = getterOrSetterMethod.getSimpleName().toString();
if ( methodName.startsWith( "change") {
return IntrospectorUtils.decapitalize( methodName.substring( 6 );
}
return super.getPropertyName( getterOrSetterMethod );
}
}
You can of course adapt the CustomAccessorNamingStrategy to fit your needs. Keep in mind that this would be used for all objects. Also the ItemDto.
More information about it can be found here in the MapStruct documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With