Mapping between objects with constant value

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

Lets say you have to map “Student” object to “StudentDTO” object. Below is the class structure for your reference.

Student

package package22;

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

    //removed getter, setter, and toString for brevity
}

StudentDTO

package package22;

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

    //removed getter, setter, and toString for brevity
}

You can see there is one extra field in “StudentDTO” class named “className” which is not there in “Student” class.

So when mapping “Student” to “StudentDTO”, we can tell MapStruct to set “className” to constant value.

The constant value to be used is set by you in the mapper interface.

So below is how we create mapper interface which will tell MapStruct to set “className” attribute on “StudentDTO” class to constant value “First”.

Mapper interface

package package22;

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

@Mapper
public interface StudentMapper {
    @Mapping(target = "className", constant = "First")
    StudentDTO getDTOFromModel(Student student);
}

As you can see in the above code snippet, we are using “Mapping” annotation and set the target attribute to “className” and constant attribute to “First”.

Please note when using “constant” attribute of “Mapping” annotation you shouldn’t use “source” attribute.

Below is the complete main method for your reference.

Main class

package package22;

import org.mapstruct.factory.Mappers;

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

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

        StudentDTO studentDTO = studentMapper.getDTOFromModel(student);
        System.out.println(studentDTO);
    }
}

Below is the output

Output

1:John Doe:First

In this way we can map one object to another using constant value.

Leave a comment