Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can only specified fields be mapped using MapStruct?

Tags:

java

mapstruct

MapStruct is mapping all the properties of source and destination by default if they have same name. The ignore element in @Mapping can be used for omitting any field mapping. But that's not I want. I want control over the mapping strategy. I want to specify something like:

@Mapper(STRATEGY=MAPPING_STRATEGY.SPECIFIED)
public interface EmployeeToEmployeeDTOMapper {
        @Mappings({
                   @Mapping(target="id", source="id"),
                   @Mapping(target="name", source="name")
                 })
        public EmployeeDTO employeeToEmployeeDTO (Employee emp);
}

Now this mapping is only meant to map id and name from source to destination. No other fields should be mapped unless specified in the mappings annotation.

like image 396
Naveen Avatar asked Mar 28 '18 06:03

Naveen


1 Answers

As of MapStruct 1.3, the @BeanMapping(ignoreByDefault = true) annotation can be added to the mapping method to achieve this result:

public interface EmployeeToEmployeeDTOMapper {
    @BeanMapping(ignoreByDefault = true)
    @Mapping(target="id", source="id")
    @Mapping(target="name", source="name")
    EmployeeDTO employeeToEmployeeDTO(Employee emp);
}

Per the Javadocs of the ignoreByDefault annotation element:

Default ignore all mappings. All mappings have to be defined manually. No automatic mapping will take place. No warning will be issued on missing target properties.

like image 112
M. Justin Avatar answered Sep 26 '22 08:09

M. Justin