How to skip a field during map stage?

user2323036 picture user2323036 · Jun 8, 2016 · Viewed 11.1k times · Source

I'm having list of employee objects - List I need to convert it into list of employee transfer objects - List

Assume a field "password" exist in both the classes.

  • In few cases i need the password needs to be included from Employee → EmployeeDTO
  • In few cases i don't need the password and want to be excluded from Employee - EmployeeDTO.

Sample Code Snippet:

    List<Employee> employees = employeeRepository.findAll();
    // Define the target type
    Type targetListType = new TypeToken<List<EmployeeDTO>>() {}.getType();
    List<EmployeeDTO> employeeDTOs = modelMapper.map(employees, targetListType);

Please let me know how to skip the fields on mapping/copying.

Answer

Pau picture Pau · Aug 2, 2016

Take a look the official user manual of Conditional Mapping.

In brief:

You would need to add a new Mapping and use a Condition. Your source and destionation would be:

  • Source: Employee
  • Destination: EmployeeDto

First create and custom your Condition. It would be something like this:

Condition<?, ?> isNotZero = new Condition<PersonDTO, Employee>() {
    public boolean applies(MappingContext<PersonDTO, Employee> context) {
      //Your conidition
      return context.getSource().getEmployeeId() != 0;
    }
  };

Then add Mapping and use the condition:

modelMapper.addMappings(new PropertyMap<PersonDTO, Person>() {
      protected void configure() {
        when(isNotZero).map(source).setEmployee(null);
      }
    });

You can find this examples in the ModelMapper GitHub repository. The author has done few more and are well explained:

  • Link to above example