Mapstruct: Ignore specific field only for collection mapping

Dmitry Kach picture Dmitry Kach · Mar 14, 2017 · Viewed 30.3k times · Source

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?

Answer

Filip picture Filip · Mar 14, 2017

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.

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

You can find more information here in the documentation.