Manthan Jamdagni
Manthan Jamdagni

Reputation: 1021

MapStruct utilize Mappings from a method into another method having return type of an inherent class

I have started using MapStruct recently and had this doubt. So is it possible to inherit mappings from one method into another method which is being used for mapping a subclass of the previous method's output.

For eg - If I have a class Car which needs to be mapped into two classes FourWheeler and DetailedFourWheeler(which extends the FourWheeler class) can I use the Mappings defined for the conversion of Car to FourWheeler into my method which converts Car to DetailedFourWheeler? Here is the example code -

@lombok.Data
public class Car {
    private String color;
    private String brand;
    private String variant;
}

@lombok.Data
public class FourWheeler {
    private String paint;
    private String company;
}

@lombok.Data
public class DetailedFourWheeler extends FourWheeler {
    private String model;
}

My Mapper for this looks like -

@Mapper
interface FourWheelerMapper {

    public static final FourWheelerMapper INSTANCE = Mappers.getMapper(FourWheelerMapper.class);

    @Mappings({
            @Mapping(source = "color", target = "paint"),
            @Mapping(source = "brand", target = "company")
    })
    FourWheeler mapToFourWheeler(Car car);

    @Mappings({
            @Mapping(source = "color", target = "paint"),
            @Mapping(source = "brand", target = "company"),
            @Mapping(source = "variant", target = "model")
    })
    DetailedFourWheeler mapToDetailedFourWheeler(Car car);
}

I want to know if it is possible to change the mapToDetailedFourWheeler like -

@InheritMappingsFromParent
@Mappings({
    @Mapping(source = "variant", target = "model")
})
DetailedFourWheeler mapToDetailedFourWheeler(Car car);

Here my InheritMappingsFromParent should bring in the mappings for color and brand from the previous method.

I was not able to find something relevant to this in the documentation. Thanks

Upvotes: 3

Views: 4644

Answers (1)

Filip
Filip

Reputation: 21393

MapStruct has the @InheritConfiguration annotation that will do what you are looking for. Have a look at Mapping configuration inheritance in the documentation for more information.

In any case for you it will not work if DetailedFourWheeler does not extend FourWheeler, since without that there is no way for MapStruct to know that the types are related.

Upvotes: 1

Related Questions