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

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

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

问题

我有一个枚举:

  1. public enum TagClassEnum {
  2. COMMON(0, "common");
  3. Integer code;
  4. String desc;
  5. }

还有两个类:

  1. class TagDTO {
  2. private TagClassEnum tagClass;
  3. }
  4. class TagPO {
  5. private Integer tagClass; // this refers TagClassEnum's code
  6. }

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

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

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

英文:

I have a enum:

  1. public enum TagClassEnum {
  2. COMMON(0, "common");
  3. Integer code;
  4. String desc;
  5. }

and two bean:

  1. class TagDTO {
  2. private TagClassEnum tagClass;
  3. }
  4. class TagPO {
  5. private Integer tagClass; // this refers TagClassEnum's code
  6. }

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

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

Is there any elegant way to do so?

答案1

得分: 2

这应该做到这一点。从 enumIntegerString 的映射使用该 enum 的字段是相当直观的,并且在主页上有很好的描述 https://mapstruct.org/

  1. @Mapping(target = "tagClass", source = "tagClass.code")
  2. TagPO tagDto2Po(TagDTO tagDTO);
  1. TagDTO tagDTO = new TagDTO(TagClassEnum.COMMON); // COMMON(0, "common")
  2. TagPO tagPO = tagMapper.tagDto2Po(tagDTO); // 自动注入的实例
  3. 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/.

  1. @Mapping(target = "tagClass", source = "tagClass.code")
  2. TagPO tagDto2Po(TagDTO tagDTO);
  1. TagDTO tagDTO = new TagDTO(TagClassEnum.COMMON); // COMMON(0, "common")
  2. TagPO tagPO = tagMapper.tagDto2Po(tagDTO); // autowired instance
  3. 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:

确定