Reputation: 749
I have two MapStruct mapper classes where some of the target/source classes and some of the fields are exactly the same:
///Mapper 1
@Mappings({
@Mapping(target = "tenantTitleId", expression = "java(order.getProductID())"),
@Mapping(target = "tenantId", constant = "MGM"),
@Mapping(target = "titleName", expression = "java(order.getProductDesc())"),
@Mapping(target = "orders", source = "order", qualifiedBy = ComplexMapper.class),
})
@BeanMapping(ignoreByDefault = true)
public abstract TargetClass toTargetClass(SourceClass sourceClass) throws Exception;
///Mapper 2
@Mappings({
@Mapping(target = "tenantTitleId", expression = "java(order.getProductID())"),
@Mapping(target = "tenantId", constant = "MGM"),
@Mapping(target = "titleName", expression = "java(order.getProductDesc())"),
@Mapping(target = "orders", source = "order", qualifiedBy = AnotherComplexMapper.class),
})
@BeanMapping(ignoreByDefault = true)
public abstract TargetClass toTargetClass(SourceClass sourceClass) throws Exception;
The first 3 mappings are exactly the same. Is there a way to not repeat this mapping the MapStruct way?
Upvotes: 1
Views: 4605
Reputation: 21403
You can use Mapping Composition in order to avoid the duplication.
e.g.
@Retention(RetentionPolicy.CLASS)
@Mapping(target = "tenantTitleId", expression = "productID")
@Mapping(target = "tenantId", constant = "MGM")
@Mapping(target = "titleName", expression = "productDesc")
public @interface CommonMappings { }
And then your mapper will look like:
///Mapper 1
@CommonMappings
@Mapping(target = "orders", source = "order", qualifiedBy = ComplexMapper.class)
@BeanMapping(ignoreByDefault = true)
public abstract TargetClass toTargetClass(SourceClass sourceClass) throws Exception;
///Mapper 2
@CommonMappings
@Mapping(target = "orders", source = "order", qualifiedBy = AnotherComplexMapper.class)
@BeanMapping(ignoreByDefault = true)
public abstract TargetClass toTargetClass(SourceClass sourceClass) throws Exception;
Upvotes: 4