Naveen
Naveen

Reputation: 473

How can only specified fields be mapped using 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.

Upvotes: 15

Views: 20205

Answers (2)

M. Justin
M. Justin

Reputation: 21123

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.

Upvotes: 16

Filip
Filip

Reputation: 21403

What you are looking for is a feature request in #1392. There is a pending PR so it would be available to use in the next version (1.3.0). The final API is not yet defined. Follow the issue and the PR to be notified when it gets done

Upvotes: 5

Related Questions