web-dev-qa-db-fra.com

De la chaîne à l'énumération en utilisant mapstruct

Je veux convertir String en enum en utilisant mapstruct

enum TestEnum {
   NO("no");
   String code;

   TestEnum(String code) {
     this.code = code
   }

   public String getCode() {
    return code;
   }
}

J'ai un code que j'ai obtenu du service et je veux convertir ce code en Enum comment le faire de manière plus simple par mapstruct

5
m.zemlyanoi

Voici une solution avec un mappeur abstrait, mais si vous le souhaitez, vous pouvez le convertir avec une méthode ou une classe par défaut

@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;
    }
}
3
Bertrand Cedric

Le code suivant a fonctionné pour moi.

@Mappings({
        @Mapping(source = "genderDTO.name", target = "genderName")
})
GenderRecord dtoTogenderRecord(GenderDTO genderDTO);
  • "genderName" est l'énumération
  • "genderDTO.name" est la chaîne

Le résultat a été:

@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;
}

J'utilise également les éléments suivants au niveau de l'interface pour garantir des contrôles nuls:

@Mapper(nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS)
2
jpCharger

MapStruct appelle uniquement la fonction "setProperty (PropertyType)", utilisez donc simplement le polymorphisme dans vos setters

Pour DTO:

    public void setStatus(String status) {
        this.status = status;
    }

    public void setStatus(ProjectStatus status) {
        this.status = status.toString();
    }

Pour l'entité:

    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;
        }
    }
1
Ryan Augustine

Dans de nombreux cas, une conversion entre le code et l'identificateur d'énumération est possible:

enum TestEnum {
   NO("no"),
   _42("42"),
   MAYBE_YES("maybe yes");

   public final String code;

   public static TestEnum fromCode(String c) {
       c = c.toUpperCase().replace(' ', '_'); // Space to underscore.
       if (c.matches("\\d.*")) {
           c = "_" + c; // Starting digit prefixed by underscore.
       }
       return TestEnum.valueOf(c);
   }

   TestEnum(String code) {
     this.code = code
   }

   public String getCode() {
    return code;
   }
}

Le champ code n'est plus nécessaire.

0
Joop Eggen