In this post under MapStruct, I will show with example how to configure MapStruct to skip particular attribute mapping from source to destination.
For our example I will use the below pojo classes as shown below
Student
package package3;
public class Student {
private int id;
private String name;
private String className;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
}
StudentDTO
package package3;
public class StudentDTO {
private int id;
private String name;
private String className;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
@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();
}
}
Next I will come up with mapper interface as shown below
StudentMapper
1 package package3;
2
3 import org.mapstruct.Mapper;
4 import org.mapstruct.Mapping;
5
6 @Mapper
7 public interface StudentMapper {
8 @Mapping(target = "className", ignore = true)
9 StudentDTO getDTOFromModel(Student student);
10 }
In the above code snippet, at line 8 we have “@Mapping” annotation, using that annotation I am telling Mapstruct to ignore mapping of attribute “className” in target DTO.
The “target” attribute will have the name of the property present in the destination object as a value and “ignore” attribute to “true”.
In this way we can instruct the MapStruct framework to skip mapping of certain attributes in the destination pojo class.
Below is the main class for your reference
Main class
package package3;
import org.mapstruct.factory.Mappers;
public class Example3 {
public static void main(String[] args) {
StudentMapper studentMapper = Mappers.getMapper(StudentMapper.class);
Student student = new Student();
student.setClassName("X");
student.setName("John");
student.setId(1);
StudentDTO studentDTO = studentMapper.getDTOFromModel(student);
System.out.println(studentDTO);
}
}