Java Mapstruct:仅针对集合映射忽略特定字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42787031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mapstruct: Ignore specific field only for collection mapping
提问by Dmitry Kach
I am using following mapper to map entities:
我正在使用以下映射器来映射实体:
public interface AssigmentFileMapper {
AssigmentFileDTO assigmentFileToAssigmentFileDTO(AssigmentFile assigmentFile);
AssigmentFile assigmentFileDTOToAssigmentFile(AssigmentFileDTO assigmentFileDTO);
@Mapping(target = "data", ignore = true)
List<AssigmentFileDTO> assigmentFilesToAssigmentFileDTOs(List<AssigmentFile> assigmentFiles);
List<AssigmentFile> assigmentFileDTOsToAssigmentFiles(List<AssigmentFileDTO> assigmentFileDTOs);
}
I need to ignore the "data" field only for entities that mapped as collection.
But it looks like @Mapping
works only for single entities. Also I've noticed that generated method assigmentFilesToAssigmentFileDTOs
just uses assigmentFileToAssigmentFileDTO
in for-loop. Is there any solution for that?
我只需要忽略映射为集合的实体的“数据”字段。但它看起来@Mapping
只适用于单个实体。我也注意到生成的方法assigmentFilesToAssigmentFileDTOs
只是assigmentFileToAssigmentFileDTO
在 for 循环中使用。有什么解决办法吗?
采纳答案by Filip
MapStruct uses the assignment that it can find for the collection mapping. In order to achieve what you want you will have to define a custom method where you are going to ignore the data
field explicitly and then use @IterableMapping(qualifiedBy)
or @IterableMapping(qualifiedByName)
to select the required method.
MapStruct 使用它可以为集合映射找到的分配。为了实现您想要的,您必须定义一个自定义方法,您将在其中data
显式忽略该字段,然后使用@IterableMapping(qualifiedBy)
或@IterableMapping(qualifiedByName)
选择所需的方法。
Your mapper should look like:
您的映射器应如下所示:
public interface AssigmentFileMapper {
AssigmentFileDTO assigmentFileToAssigmentFileDTO(AssigmentFile assigmentFile);
AssigmentFile assigmentFileDTOToAssigmentFile(AssigmentFileDTO assigmentFileDTO);
@IterableMapping(qualifiedByName="mapWithoutData")
List<AssigmentFileDTO> assigmentFilesToAssigmentFileDTOs(List<AssigmentFile> assigmentFiles);
List<AssigmentFile> assigmentFileDTOsToAssigmentFiles(List<AssigmentFileDTO> assigmentFileDTOs);
@Named("mapWithoutData")
@Mapping(target = "data", ignore = true)
AssignmentFileDto mapWithouData(AssignmentFile source)
}
You should use org.mapstruct.Named
and not javax.inject.Named
for this to work. You can also define your own annotation by using org.mapstruct.Qualifier
你应该使用org.mapstruct.Named
而不是javax.inject.Named
为了这个工作。您还可以通过使用定义自己的注释org.mapstruct.Qualifier
You can find more information here in the documentation.
您可以在此处的文档中找到更多信息。