【问题标题】:Mapstruct : map field conditionally or ignoreMapstruct :有条件地映射字段或忽略
【发布时间】:2020-04-24 14:42:11
【问题描述】:

我有一堂这样的课:

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

仅当标志 isFailed 为真时,我想将 failedCourses 列表从 StudentDTO 映射到 Student,否则忽略该字段,但不使用接口中的默认实现。 mapstruct 中是否有任何注释/参数可以帮助我?我试过使用expression,但不能让它工作。

【问题讨论】:

    标签: java spring mapping mapstruct


    【解决方案1】:

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

    @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 );
           }
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-28
      • 2017-08-04
      • 2016-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 1970-01-01
      • 2021-10-09
      相关资源
      最近更新 更多