如何使用MapStruct将枚举映射到其自身属性?

huangapple go评论73阅读模式
英文:

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);

有没有一种优雅的方法来实现这个映射呢?

英文:

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?

答案1

得分: 2

这应该做到这一点。从 enumIntegerString 的映射使用该 enum 的字段是相当直观的,并且在主页上有很好的描述 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);         // 自动注入的实例

log.debug(tagPO.getTagClass());                    // 输出 0

反过来要困难一些,需要使用 Java 表达式@AfterMapping 来解析 enum

英文:

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.

huangapple
  • 本文由 发表于 2020年10月23日 18:04:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/64497947.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定