[英]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
的字段从enum
到Integer
或String
的映射非常简单,并且在主页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
另一种方法有点困难,需要使用 Java 表达式或@AfterMapping
进行enum
解析。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.