简体   繁体   中英

Mapstruct : map field conditionally or ignore

I have a class something like this :

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

I want to map failedCourses List from StudentDTO to Student only if the flag isFailed is true, else ignore the field, but without using default implementation in interface. Is there any annotation/paramater in mapstruct that can help me? I've tried using expression but can't make it work.

There are several approaches. But, they all come down writing some custom code to do this:

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

You could also make a dedicated mapping for one property and use the entire source as input.. Like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM