Mapstruct :有条件地映射字段或忽略

Mapstruct : map field conditionally or ignore

我有一个 class 像这样的东西:

class StudentDTO {
    String name;
    Integer rollNo;
    List<CourseDTO> coursesTaken;
    Boolean isFailed;
    List<CourseDTO> failedCourses;
}

仅当标志 isFailed 为真时,我想将 failedCourses 列表从 StudentDTO 映射到 Student,否则忽略该字段,但不使用接口中的默认实现。 mapstruct 中有 annotation/paramater 可以帮助我吗?我试过使用 expression 但无法正常工作。

有几种方法。但是,他们都写了一些自定义代码来做到这一点:

@Mapper
public interface MyMapper{

   @Mapping( target = "failedCourses", ignore = true )
   Student map(StudentDTO dto);


   List<Course> map(List<CourseDTO> courses);

   @AfterMapping
   default void map(StudentDTO dto, @MappingTarget Student target) {
       if (dto.isFailed() ) {
           target.setFailedCourses( map( dto.getFailedCourses() );
       }
   }
}

您也可以为其中一个 属性 制作专用映射,然后使用整个源作为输入。像这样

@Mapper
public interface MyMapper{

   @Mapping( target = "failedCourses", source = "dto" )
   Student map(StudentDTO dto);

   List<Course> map(List<CourseDTO> courses);

   default List<Course> map(StudentDTO dto) {
       if (dto.isFailed() ) {
           return map( dto.courses );
       }
   }
}