Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map enum to String using Mapstruct

Tags:

mapstruct

I can find answers where we have String to Enum mapping but I can't find how can I map an Enum to a String.

public class Result {
  Value enumValue;
}

public enum Value {
   TEST,
   NO TEST
}


public class Person {
  String value;
}

How can I map this ?

I tried :

@Mapping(target = "value", source = "enumValue", qualifiedByName = "mapValue")


 @Named("mapValue")
    default Person mapValue(final Value en) {
        return Person.builder().value(en.name()).build();
    }
like image 226
newLearner Avatar asked Apr 27 '26 23:04

newLearner


2 Answers

mapstruct should support this out of the box. So @Mapping(target = "value", source = "enumValue") should suffice.

Complete example including target/source classes:


@Mapper
public interface EnumMapper {
    @Mapping( target = "value", source = "enumValue" )
    Person map(Result source);
}

class Result {
    private Value enumValue;

    public Value getEnumValue() {
        return enumValue;
    }

    public void setEnumValue(Value enumValue) {
        this.enumValue = enumValue;
    }
}

enum Value {
    TEST, NO_TEST
}

class Person {
    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

This results in the following generated code:

@Generated(
    value = "org.mapstruct.ap.MappingProcessor",
    date = "2022-02-20T12:33:00+0100",
    comments = "version: 1.5.0.Beta2, compiler: Eclipse JDT (IDE) 1.4.50.v20210914-1429, environment: Java 17.0.1 (Azul Systems, Inc.)"
)
public class EnumMapperImpl implements EnumMapper {

    @Override
    public Person map(Result source) {
        if ( source == null ) {
            return null;
        }

        Person person = new Person();

        if ( source.getEnumValue() != null ) {
            person.setValue( source.getEnumValue().name() );
        }

        return person;
    }
}
like image 103
Ben Zegveld Avatar answered Apr 30 '26 13:04

Ben Zegveld


I faced with the same issue.
But this doesn't work if your Enum isn't nested/inner class or if you need more complex logic. After generation with Mapstruct your import is invalid, so i fixed it with another approach.

  1. Create the default method with getting required data:
    default String getEnumValue(Result source) {
     return source.getEnumValue().name();
    }
  1. Call this method in your mapping:
    @Mapping( target = "value", expression = "java(getEnumValue(source))")
    Person map(Result source);
like image 26
Alexander Yushko Avatar answered Apr 30 '26 12:04

Alexander Yushko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!