[英]Can not map Enum value with @mapper
I'm trying to make an automatic mapper, but I'm having a problem with an Enum
inside my DTO.我正在尝试制作一个自动映射器,但我的 DTO 中的
Enum
有问题。 In my @mapper
class, I want everything to be automatically mapped except fthe Enum
field.在我的
@mapper
class 中,我希望自动映射除Enum
字段之外的所有内容。 However, when debugging, I see that it does go into the mapper auto-implementation class, and it doesn't ignore my Enum
as I indicate with @mapping但是,在调试时,我看到它确实 go 进入映射器自动实现 class,并且它不会像我用 @mapping 指示的那样忽略我的
Enum
Example of my Entity and DTO我的实体和 DTO 示例
@Entity
public class Document {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
private String type;
My DTO:我的 DTO:
@Data
public class DocumentDTO {
private Integer id;
private DocumentsEnum type;
How can I ignore the mapping for that specific enumerated field?如何忽略该特定枚举字段的映射?
I have tried the following annotations on @mapping:我在@mapping 上尝试了以下注释:
@Mapper
public interface DocumentsMapper {
@Mapping(source = "type", target = "type", ignore = true)
@Mapping(source = "DocumentsEnum", target = "DocumentsEnum", ignore = true)
@Mapping(source = "MAIN", target = "MAIN", ignore = true) // <-- This is the value of Enum
@Mapping(source = "ppal", target = "ppal", ignore = true) // <-- This is the name of Enum
List<DocumentDTO> mapper(List<Document> document);
@AfterMapping
default void afterMapping(Document document, @MappingTarget DocumentDTO documentDTO) {
//some logic
}
The correct way to declare your Mapping
to ignore the field you want to ignore is the first one, you can delete the others.声明你的
Mapping
忽略你想忽略的字段的正确方法是第一个,你可以删除其他的。
@Mapping(source = "type", target = "type", ignore = true)
The reason that this isn't working for you as written is that you are technically mapping a List
object to another List
object. The List
objects you pass in to be mapped will probably not have a type
field (and definitely not the one you care about), the objects they hold ( Document
and DocumentDTO
) will though.这对您不起作用的原因是您在技术上将
List
object 映射到另一个List
object。您传入要映射的List
对象可能没有type
字段(而且绝对不是您关心的类型字段)关于),它们持有的对象( Document
和DocumentDTO
)将会。
To get this to work they way you would like you need two mappers: one for the List
s and one for Document
to DocumentDTO
.为了使它按照他们的方式工作,您需要两个映射器:一个用于
List
,一个用于Document
到DocumentDTO
。 Since the type
field you want to ignore is on the latter objects, you should put the Mapping
annotation on that method:由于您要忽略的
type
字段位于后面的对象上,因此您应该将Mapping
注释放在该方法上:
@Mapper
public interface DocumentsMapper {
List<DocumentDTO> listMapper(List<Document> document);
@Mapping(source = "type", target = "type", ignore = true)
DocumentDTO mapper(Document document);
The mapstruct
library is smart enough to automatically use the mapper
method to convert each element in your List
in the listMapper
method. mapstruct
库足够智能,可以自动使用mapper
方法在listMapper
方法中转换List
中的每个元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.