12

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.

M. Justin
  • 14,487
  • 7
  • 91
  • 130
Naveen
  • 403
  • 1
  • 6
  • 20

2 Answers2

10

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.

M. Justin
  • 14,487
  • 7
  • 91
  • 130
5

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

Filip
  • 19,269
  • 7
  • 51
  • 60
  • 2
    Only by explicitly using `@Mapping(target = "foo", ignore = true)` – Filip Mar 28 '18 at 18:53
  • Thanks @Filip. Any idea when this said feature will be available? And can you please upvote my question if you think it deserves. Because I'm low on reputation. – Naveen Mar 30 '18 at 02:33
  • It would come in 1.3.0. Which is soonish. There is one big PR [#1373](https://github.com/mapstruct/mapstruct/pull/1373) that we need to merge and that one is almost done. Once it is there it should be really fast for us to do the release – Filip Mar 30 '18 at 09:20
  • Thanks Filip. I can wait for that. Can you please answer the following as well. https://stackoverflow.com/questions/49570864/how-to-map-jaxb-elements-annotated-with-xmlseealso-using-mapstruct – Naveen Mar 30 '18 at 09:33
  • This was released in February 2019: https://stackoverflow.com/a/67116426/1108305 – M. Justin Apr 08 '22 at 14:49