Using source object in expressions

In this post under MapStruct, I will show with example, how to use source object in our expressions.

For our example, lets say we have to map “Student” object to “StudentDTO” object.

Below are their class structures

Student

package package25;

public class Student {
    private int id;
    private String firstName;
    private String lastName;

    //Removed the getter, setter, and toString for brevity
}

StudentDTO

package package25;

public class StudentDTO {
    private int id;
    private String name;

    //Removed the getter, setter, and toString for brevity
}

If you compare the class structure of “Student” and “StudentDTO”, you will see in “Student” class a student name is divided into “firstName” and “lastName”. Where as in “StudentDTO” class there is only one variable “name” that is used to store a concatenation of first and last name.

We need to a Mapper interface in such a way that it instructs MapStruct to combine “Student” class “firstName” and “lastName” and then assign it to “StudentDTO” class “name” variable.

We can achieve this by using the source object in the expressions.

Below is the Mapper interface

StudentMapper

package package25;

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

@Mapper
public interface StudentMapper {
    @Mapping(target = "name", expression = "java(student.getFirstName() + ' ' + student.getLastName())")
    StudentDTO getDTOFromModel(Student student);
}

In the above code snippet, we have used the source object “student” in the expression to access “firstName” and “lastName” to combine them and return the concatenation as a result of the expression.

The result of the expression is then assigned to “name” variable of “StudentDTO” class object.

In this way we can access source object in the expressions.

Below is the main class for your reference

Main class

package package25;

import org.mapstruct.factory.Mappers;

public class Example25 {
    public static void main(String[] args) {
        StudentMapper studentMapper = Mappers.getMapper(StudentMapper.class);

        Student student = new Student();
        student.setId(1);
        student.setFirstName("John");
        student.setLastName("Doe");

        StudentDTO studentDTO = studentMapper.getDTOFromModel(student);

        System.out.println(studentDTO);
    }
}

Leave a comment