Conditional mapping example

In this post under MapStruct, I will show with example how to achieve conditional mapping.

Till now in all my previous example, I used to configure which source property should be mapped to which target property and MapStruct would follow that.

What if we want to tell MapStruct, do the mapping only if a particular condition is true, if not don’t do the mapping. This is called Conditional mapping.

Conditional mapping is possible in MapStruct.

Let me show you an example of how to do it.

For our example, let us map “Student” object to “StudentDTO” object.

Below are the structure of both “Student” and “StudentDTO” object.

Student

package package37;
public class Student {
private int id;
private String name;
private String className;
//Removed getter, setter, and toString for brevity
}

StudentDTO

package package37;
public class StudentDTO {
private int id;
private String name = "JohnDoe"; //default values
private String className = "First"; //default values
//Removed getter, setter, and toString for brevity;
}

Now the condition is to map String property “name” and “className” in source object to target object properties only if the source property value is not null or empty.

We will add this condition in the mapper interface itself using MapStruct’s “@Condition” annotation

Below is the mapper interface structure

StudentMapper

package package37;
import org.mapstruct.Condition;
import org.mapstruct.Mapper;
@Mapper
public interface StudentMapper {
StudentDTO getDTOFromModel(Student student);
@Condition
default boolean isNotEmpty(String value) {
return value != null && !value.isEmpty();
}
}

In the above interface, I have added the condition as a default method named “isNotEmpty” and annotated it with “@Condition” annotation.

Now whenever a source property of type String is about to be mapped to target object property, this method is called and if this method returns true, mapping is done or else skipped.

Below is the complete main class for your reference

Main class

package package37;
import org.mapstruct.factory.Mappers;
public class Example37 {
public static void main(String[] args) {
StudentMapper studentMapper = Mappers.getMapper(StudentMapper.class);
Student student = new Student();
student.setId(1);
StudentDTO studentDTO = studentMapper.getDTOFromModel(student);
System.out.println(studentDTO);
}
}

Below is the output for your reference

Output

1:JohnDoe:First

As you can see from the output, “name” and “className” property of “StudentDTO” still using default values even after mapping.

Leave a comment