I want to convert String to enum using mapstruct
enum TestEnum {
   NO("no");
   String code;
   TestEnum(String code) {
     this.code = code
   }
   public String getCode() {
    return code;
   }
}
I have a code that I've got from service and I want to convert this code to Enum how to do it with easier way by mapstruct
The following code worked for me.
@Mappings({
        @Mapping(source = "genderDTO.name", target = "genderName")
})
GenderRecord dtoTogenderRecord(GenderDTO genderDTO);
The result was:
@Override
public GenderRecord dtoTogenderRecord(GenderDTO genderDTO) {
    if ( genderDTO == null ) {
        return null;
    }
    GenderRecord genderRecord = new GenderRecord();
    if ( genderDTO.getName() != null ) {
        genderRecord.setGenderName( Enum.valueOf( GenderType.class, genderDTO.getName() ) );
    }
    return genderRecord;
}
I also use the following at the interface level to ensure null checks:
@Mapper(nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS)
                        MapStruct only calls the "setProperty(PropertyType)" function, so simply use polymorphism in your setters
For DTO:
    public void setStatus(String status) {
        this.status = status;
    }
    public void setStatus(ProjectStatus status) {
        this.status = status.toString();
    }
For Entity:
    public void setStatus(ProjectStatus status) {
        this.status = status;
    }
    public void setStatus(String status) {
        switch (status) {
        case "PENDING_WITH_RM":
            this.status = ProjectStatus.PENDING;
            break;
        case "PENDING_WITH_OPS":
            this.status = ProjectStatus.PENDING;
            break;
        case "COMPLETED":
            this.status = ProjectStatus.COMPLETED;
            break;
        default:
            this.status = ProjectStatus.DRAFT;
        }
    }
                        Here is a solution with an abstract mapper, but if you want you can convert it with a default methode or a class
@Mapper
public abstract class TestMapper {
    abstract Source toSource(Target target);
    abstract Target totarget(Source source);
    String toString(TestEnum test){
        return test.getCode();
    }
    TestEnum toEnum(String code){
        for (TestEnum testEnum : TestEnum.values()) {
            if(testEnum.equals(code)){
                return testEnum;
            }
        }
        return null;
    }
}
public class Source {    
    String value;    
    public String getValue() {
        return value;
    }    
    public void setValue(String value) {
        this.value = value;
    }    
}
public class Target {
    TestEnum value;
    public TestEnum getValue() {
        return value;
    }
    public void setValue(TestEnum value) {
        this.value = value;
    }
}
                        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