如何使用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(列表到列表)。
答案 0 :(得分:3)
首先,Source
始终包含一个课程,为什么不将其设为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);
}
如果Course
不是列表。那么你可以用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);
}