MapStruct – Easy & fast way to map Java beans

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;
class Employee {
    Employee(int id, String name, String email) {
        this.id = id;
        this.employeeName = name;
        this.email = email;
    }
    private int id;
    private String employeeName;
    private String email;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getEmployeeName() {
        return employeeName;
    }
    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
}
class EmployeeDTO {
    private int id;
    private String name;
    private String email;
    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 getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
}
@Mapper
interface EmployeeMapper {
    EmployeeMapper INSTANCE = Mappers.getMapper(EmployeeMapper.class);
    //Mapping is needed only for the attributes which have different names in source and target class
    @Mapping(source = "employeeName", target = "name")
    EmployeeDTO employeeToEmployeeDTO(Employee employee);
}
public class TestMapper {
    public static void main(String a[]) {
        Employee employee = new Employee(109, "Peter", "peter@testemail.com");
        //Below mapper will create EmployeeDTO object from Employee object and populate the values from it.
        EmployeeDTO userDTO = EmployeeMapper.INSTANCE.employeeToEmployeeDTO(employee);
        System.out.println(userDTO.getEmail());
        System.out.println(userDTO.getId());
        System.out.println(userDTO.getName());
    }
}    

Output:

peter@testemail.com
109
Peter

Leave a comment