ArchCST
ArchCST

Reputation: 135

How to map enum to it's own property with MapStruct?

I have a enum:

public enum TagClassEnum {
    COMMON(0, "common");

    Integer code;
    String desc;
}

and two bean:

class TagDTO {
    private TagClassEnum tagClass;
}

class TagPO {
    private Integer tagClass; // this refers TagClassEnum's code
}

Now I want to map the enum to code with MapStruct:

@Mappings({@Mapping(source = ???, target = ???)})
TagPO tagDto2Po(TagDTO tagDTO);

Is there any elegant way to do so?

Upvotes: 1

Views: 4329

Answers (1)

Nikolas
Nikolas

Reputation: 44398

This should do that. The mapping from enum into an Integer or String using the fields of that enum is fairly straightforward and well described at the home page https://mapstruct.org/.

@Mapping(target = "tagClass", source = "tagClass.code")
TagPO tagDto2Po(TagDTO tagDTO);
TagDTO tagDTO = new TagDTO(TagClassEnum.COMMON);   // COMMON(0, "common")
TagPO tagPO = tagMapper.tagDto2Po(tagDTO);         // autowired instance

log.debug(tagPO.getTagClass());                    // prints 0               

The other way around is a bit harder and would require the enum resolution using either a Java expression or @AfterMapping.

Upvotes: 3

Related Questions