Search code examples
javaenumsmapstruct

Map enums with mapstruct


I have to make custom mappers on the application I’m working on. Some properties are enum types like this. I’m trying to figure out how to create a map in this situation.

Here's the property of the entity:

@JsonProperty("csp")
private JsonNullable<Csp> csp = JsonNullable.undefined();

where Csp is an enum

Here's the property of the dto I want to map:

private String profession;

Here's the map that’s not good:

@Mapping(target = "assure", source = "assure", qualifiedByName = "toAssureDto")

@Named("toAssureDto")
@Mapping(target = "profession", source = "csp")
AssureDto toDto(final AssureAuto entity);

Thanks for help


Solution

  • Solution 1 (expressions):

    @Named("toAssureDto")
    //assuming csp is not null, and that I want to map the value of the enum returned by .toString() that can be different from .name()
    @Mapping(target = "profession", expression = "java(entity.getCsp().get().toString())")
    AssureDto toDto(final AssureAuto entity);
    

    Solution 2 (adding-custom-methods):

    @Named("toAssureDto")
    @Mapping(target = "profession", source = "csp", qualifiedByName = "mapCsp")
    AssureDto toDto(final AssureAuto entity);
    
    @Named("mapCsp") 
    default String mapCsp(JsonNullable<Csp> csp){
        //add your custom mapping implementation
        //here is an example assuming csp is not null, and that I want to map the value of the enum returned by .toString() that can be different from .name()
        return csp.get().toString();
    }
    

    Other Documentation: