英文:
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
这应该做到这一点。从 enum
到 Integer
或 String
的映射使用该 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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论