简体   繁体   中英

Default value to another bean property when Source is null MapStruct

Well, I have the following Mapper in MapStruct:

 @Mapping(source = "payload.after", target = "payload")
 TargetEntity toTarget(SourceEntity source);

Sometimes payload.after is null and I need to fill with another property, called payload.before . Something like this:

 @Mapping(source = "payload.after", target = "payload")
   //OR, if payload.after is null
 @Mapping(source = "payload.before", target = "payload")
 TargetEntity toTarget(SourceEntity source);

I tried used in this way but didn't work:

 @Mapping(source = "payload.after", target = "payload", defaultValue = "payload.before")
 TargetEntity toTarget(SourceEntity source);

Is there a way to do it?

From MapStruct docs I see that only you can use predefined values: https://mapstruct.org/documentation/stable/reference/html/#default-values-and-constants

But you can easily do it by using annotations like @AfterMapping or @BeforeMapping check in MapStruct docs examples :)

EDIT:

@Mapping(target = "otherTargetField", source = "otherSrcField")
TargetEntity toTarget(SourceEntity source);

@AfterMapping
void toTargetAfterMapping(@MappingTarget TargetEntity, SourceEntity source) {
   // Your after mapping logic with payload.before and payload.after
}

MapStruct auto-resolves that this method is called at the end of the mapping method before the last return statement. If you want to know more see MapStruct docs - customising mappings with before and after .

Another approach which you can use is a defaultExpression

@Mapping(target = "payload", source = "payload.after", defaultExpression = "java(source.getPayload().getBefore())")
TargetEntity toTarget(SourceEntity source);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM