我有一堂这样的课:
class StudentDTO {
String name;
Integer rollNo;
List<CourseDTO> coursesTaken;
Boolean isFailed;
List<CourseDTO> failedCourses;
}
仅当标志failedCourses
为true时,我才想将isFailed
列表从StudentDTO映射到Student,否则忽略该字段,但不使用接口中的默认实现。 mapstruct中是否有任何注释/参数可以帮助我?我尝试使用expression
,但无法正常工作。
答案 0 :(得分: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 );
}
}
}