gpt4 book ai didi

java - 映射结构 : map field conditionally or ignore

转载 作者:行者123 更新时间:2023-12-01 19:02:01 25 4
gpt4 key购买 nike

我有一个类似这样的类(class):

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

仅当标志 isFailed 为 true 时,我才想将 failedCourses 列表从 StudentDTO 映射到 Student,否则忽略该字段,但不使用接口(interface)中的默认实现。 mapstruct 中是否有任何注释/参数可以帮助我?我尝试过使用表达式,但无法使其工作。

最佳答案

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

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

关于java - 映射结构 : map field conditionally or ignore,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59622534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com