如何使用 MapStruct 将枚举映射到它自己的 属性?

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

我有一个枚举:

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

    Integer code;
    String desc;
}

和两个豆子:

class TagDTO {
    private TagClassEnum tagClass;
}

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

现在我想使用 MapStruct 将枚举映射到代码:

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

有什么优雅的方法吗?

这应该能做到。使用 enum 的字段从 enumIntegerString 的映射相当简单,在主页 https://mapstruct.org/.[=20 中有详细描述=]

@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               

另一种方法有点难,需要使用 Java expression or @AfterMapping.

enum 分辨率