1
votes

I am using Mapstruct to map from generated DTOs (metro, xsd) to our business domain objects. My difficulty is that the DTOs don't actually reference child objects but instead use IDs to reference associated instances.

Trying to break this down to a simplified case, I have come up with an example:

  1. SchoolDTO has a lists of teachers and courses. The teacher of a course is only referenced through a teacherId in each course.

  2. In the business domain School only has a list of teachers who each hold a list of their courses.

Class diagram: UML: DTO / Domain

Initially I was hoping to solve this in mapstruct syntax with something like a join on foreignId and teacher id (or some qualifiedBy association), pseudo code as follows:

@Mapping(source="courses", target="teachers.courses", where="teacher.id = course.teacherId")

DTOs:

public class SchoolDto {
    List<TeacherDto> teachers;
    List<CourseDto> courses;
}

public class TeacherDto {
    String id;
    String name;
}

public class CourseDto {
    String name;
    String teacherId;
}

Domain:

public class School {
    List<Teacher> teachers;
}

public class Teacher {
    String name;
    List<Course> courses;
}

public class Course {
    String name;
}

I am right now working around it with fairly big @AfterMapping methods but I feel this isn't such an exceptional use case - so maybe I am missing something rather obvious. What is the correct/intended way to solve these type of "joins" in a mapping with Mapstruct?

1

1 Answers

1
votes

I doubt that you can do this without an @AfterMapping. MapStruct is "just" for mapping one object to another one, it doesn't support any kind of queries to find or join data.

If you are not already using it this sounds like a good use-case for using a context. Then the @AfterMapping is not really big:

@Mapper
public abstract class SchoolMapper {
    public School toSchool(SchoolDto school) {
        return toSchool( school, school.getCourses() );
    }

    protected abstract School toSchool(SchoolDto school, @Context List<CourseDto> courses);

    @Mapping(target = "courses", ignore = true) // see afterMappingToTeacher
    protected abstract Teacher toTeacher(TeacherDto teacher, @Context List<CourseDto> courses);

    protected abstract Course toCourse(CourseDto course);

    @AfterMapping
    void afterMappingToTeacher(@MappingTarget target, TeacherDto source, @Context List<CourseDto> courses) {
        // omitted null-checks

        List<Course> courses = new ArrayList<>();
        for(CourseDto course : courses) {
            if(course.getTeacherId().equals(source.getId())) {
                courses.add( toCourse(course) );
            }
        }

        target.setCourses( courses );
    }
}

(when using Java >= 8 you can use an interface with default methods)

In case you need to query things multiple times you can things create an own class as a context which for example has own methods for finding all courses by a teacher ID.