Enum in MapStuct

Viewed 56

I have .json and enum is described in it:

"MyEnum" : {
    "enum" : [
    "1",
    "2"
    ],
    "x-enum-varnames": [
    "VAL1",
    "VAL2"
    ],
    type: "string"
}

I am using openapi-generator-maven-plugin and I get enum like this:

public enum MyEnum {
    VAL1("1"),
    VAL2("2)
}

Using mapstruct I try to map the incoming values "1" and "2" into this object, but mapstruct uses .getValue()

How can I override the use of .getValue() with .fromValue()? Or what do you recommend?

P.s.:

It's just:

@Mapper(componentModel="spring")
public interface MyEnumMapper {
    MyEnum  map(IncomeDto dto);
}

I will try to describe in more detail:

The IncomeDto object has one field Value and can have the values "1" and "2"

I'm trying to map values from IncomeDto to MyEnum, but mapStruct generates a class that uses mapping using .getValue() and the values "1" and "2" cannot map to "VAL1" and "VAL2"

1 Answers

i using mapstruct for mapper entities, usually for enum coding :

  @Mapper
    public interface StatusMapper {
      @ValueMapping(target = "ACTIVE", source = "ACTIVE")
      @ValueMapping(target = "SUBSIDIED", source = "SUB")
      @ValueMapping(target = "SUSPENDED", source = "SUS")
      @ValueMapping(target = "CANCELED", source = "CANCEL")
      StatusContract statusToEnum(StatusContractInput situation);
    }

generated code:

@Override
  public StatusContract statusToEnum(StatusContractInput situation) {
    if ( situation == null ) {
      return null;
    }

    StatusContract statusContract;

    switch ( situation ) {
      case ACTIVE: statusContract = StatusContract.ACTIVE;
        break;
      case SUB: statusContract = StatusContract.SUBSIDIED;
        break;
      case SUSPENSO: statusContract = StatusContract.SUSPENDED;
        break;
      case CANCEL: statusContract = StatusContract.CANCELED;
        break;
      default: throw new IllegalArgumentException( "Unexpected enum constant: " + situation );
    }

    return statusContract;
  }

In output value string:

@Mapping(target = "situation", source = "status.description")
  ContractModel contractToModel(Contract contract);

In ContractModel the situation property is String.

for more information: https://mapstruct.org/documentation/stable/reference/html/#mapping-enum-types

A solution for string-enum:

@Mapper
public interface MyEnumMapper {

  default MyEnum map(IncomeDto dto) {
    return MyEnum.fromValue(dto.getValue());
  }
}
Related