Trying to make a MapStruct implementation where I have a "parent"-object like this:
public abstract class Parent {
private String id;
}
Then I have children with a whole bunch of more attributes such as:
public class ChildA extends Parent{
private String name;
//And so on...
}
public class ChildB extends Parent{
private String address;
//And so on...
}
How do I represent this data-structure in MapStruct mappers? I only want to map the children and not the parent. I have successfully made a mapper to map a child with an abstract class, but I can't get the "parent" mapping to tag along without explicitly stating it inside the child-mappers.
Is there a way I can do something like:
@Mapping(source = "id" target = "targetId")
In a parent mapper, and then inherit that mapping statement to the children? I don't want the parent to have a mapper on its own, I just want it to hold that mapping statement to reduce redundancy.
I would love to extend my abstract child-mapper class with a parent class and then simply inherit. Is this possible?
Yes it is possible.
You need to have a MapperConfig that will carry all the common configurations.
@MapperConfig(
mappingInheritanceStrategy = MappingInheritanceStrategy.AUTO_INHERIT_FROM_CONFIG
)
public interface ParentConfig {
// Not intended to be generated, but to carry inheritable mapping annotations:
@Mapping(target = "targetId", source = "id")
ParentDto entityToDto(Parent entity);
}
and then, you need to have a mapper and specify that it will have to use the ParentConfig
@Mapper(config = ParentConfig.class)
public interface ChildAMapper {
@Mapping(target = "targetName", source = "name")
// additionally inherited from ParentConfig, because ChildA extends Parent and ChildADto extends ParentDto:
// @Mapping(target = "targetId", source = "id")
ChildADto toChildADto(ChildA childA);
}
Official documentation: shared-configurations
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With