gpt4 book ai didi

mapstruct - 使用 MapStruct 进行嵌套列表映射

转载 作者:行者123 更新时间:2023-12-02 09:44:51 64 4
gpt4 key购买 nike

如何使用 MapStruct 对于以下场景进行 bean 映射。

class Source {
private String sourceId;
private List<Course> courses; //always returns only one course
}

class Course {
private String courseName;
private List<Student> students;
}

class Student {
private String studentName;
}

class Target {
private String targetId;
private String subjectName;
private List<Member> members;
}

class Member {
private String memberName;
}

现在我想将sourceId映射到targetId,将courseName映射到subjectName,将studentName映射到memberName(列表到列表)。

最佳答案

首先,Source 始终包含一门类(class),为什么不将其设为 Course 元素而不是 List

如果您这样做,映射将会简单得多。对于您当前的设置来说,它有点复杂。

@Mapper
public interface MyMapper {

@Mapping(target = "targetId", source = "sourceId")
@Mapping(target = "subjectName", source = "courses")
@Mapping(target = "members", source = "courses")
Target map(Source source);

default String subjectName(List<Course> courses) {
if (courses == null || courses.isEmpty()) {
return null;
}
return courses.get(0).getCourseName();
}

default List<Member> toMembersFromCourses(List<Course> courses) {
if (courses == null || courses.isEmpty()) {
return null;
}
return toMembers(courses.get(0).getStudents());
}

List<Member> toMembers(List<Student> students);

@Mapping(target = "memberName", source = "studentName")
Member toMember(Student student);
}

如果类(class)不是列表。那么你可以用 1.2.0.Final 做得更优雅。

@Mapper
public interface MyMapper {

@Mapping(target = "targetId", source = "sourceId")
@Mapping(target = "subjectName", source = "course.courseName")
@Mapping(target = "members", source = "course.students")
Target map(Source source);

@Mapping(target = "memberName", source = "studentName")
Member toMember(Student student);
}

关于mapstruct - 使用 MapStruct 进行嵌套列表映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46841093/

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