Mapping between objects with default value

In this post under MapStruct, I will show with example how to map two objects with default value.

Let me further elaborate the requirement.

We have “Student” class and we have to map the instance of “Student” class to an instance of “StudentDTO” class. During mapping if the value of “className” attribute in “Student” class is not present, we set a default value in the instance of “StudentDTO” class and the value will be “First”.

Below is the class structure of “Student” class

Student

package package5;

public class Student {
    private int id;
    private String name;
    private String className;

    /*Removed the getter and setter for brevity*/

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(this.id).append(":");
        stringBuilder.append(this.name).append(":");
        stringBuilder.append(this.className);
        return stringBuilder.toString();
    }
}

Below is the class structure of “StudentDTO” class

StudentDTO

package package5;

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

    /*Removed the getter and setter for brevity*/

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(this.id).append(":");
        stringBuilder.append(this.name).append(":");
        stringBuilder.append(this.className);
        return stringBuilder.toString();
    }
}

Below is the Mapper interface “StudentMapper”

StudentMapper

1  package package5;
2  
3  import org.mapstruct.Mapper;
4  import org.mapstruct.Mapping;
5  
6  @Mapper
7  public interface StudentMapper {
8      @Mapping(target = "className", defaultValue = "First")
9      StudentDTO getDTOFromModel(Student student);
10 }

In the above Mapper interface, at line 8, using the “@Mapping”, we are instructing the MapStruct that when mapping attributes from “Student” object to “StudentDTO” object. If it didn’t find any value for “className” attribute in “Student” object, then set the “className” attribute in “StudentDTO” object to “First”.

In this way we can map two objects with default value.

Below is the complete main code for your reference.

Main class

package package5;

import org.mapstruct.factory.Mappers;

public class Example5 {
    public static void main(String[] args) {
        StudentMapper studentMapper = Mappers.getMapper(StudentMapper.class);
        Student student = new Student();
        student.setName("John");
        student.setId(1);
        StudentDTO studentDTO = studentMapper.getDTOFromModel(student);
        System.out.println(studentDTO);

        student = new Student();
        student.setName("John");
        student.setId(1);
        student.setClassName("Second");
        studentDTO = studentMapper.getDTOFromModel(student);
        System.out.println(studentDTO);
    }
}

Leave a comment