Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapstruct inherit @Mappings

Tags:

java

mapstruct

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?

like image 471
Prince of Sweden Avatar asked Sep 17 '26 04:09

Prince of Sweden


1 Answers

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

like image 194
Paul Marcelin Bejan Avatar answered Sep 19 '26 18:09

Paul Marcelin Bejan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!