javamapstructmapper

How to map the source object of type String to target UUID in MapStruct?


Here is a code snippet:

Source:

public class BuyerInfo {
   String membershipID;
}

Target:

public class BuyerInfo {
   UUID membershipID;
}

Error in console:

Can't map property "String buyerInfo.primaryMembershipID" to "UUID buyerInfo.id". Consider to declare/implement a mapping method: "UUID map(String value)".


Solution

  • I tried this and it worked for me.

    @Mapper(componentModel = "spring")
    public interface SourceToTargetMapper {
    
        SourceToTargetMapper INSTANCE = Mappers.getMapper( SourceToTargetMapper.class );
    
        @Mapping(target="buyerInfo.id" source="sourceOrder.id", qualifiedByName = "mapToUUID")
        Order sourceOrderList(SourceOrder.Order sourceOrder);
    
        @Named("mapToUUID")
        default UUID mapToBuyerInfoId(BuyerMetaData buyerInfo){
            return UUID.fromString(buyerInfo.getPrimaryMembershipID());
        }
    }