Mapstruct, multiple derived classes with differing field names

1 week ago 5
ARTICLE AD BOX

I have several classes as follows:

@Data public class Parent { long id; String name; } @Data public class Child extends Parent { String nickName; } @Data public class Grandchild extends Child { int count; }

and their associated dtos:

@Data public class ParentDto { long idDto; String name; } @Data public class ChildDto extends ParentDto { String nickNameDto; } @Data public class GrandchildDto extends ChildDto { int countDto; }

I am trying to create the corresponding mappers/mapperconfigs that will describe the mappings from Object to ObjectDto. If I define a mapperconfig for ParentToParentDto as:

@MapperConfig(mappingInheritanceStrategy = MappingInheritanceStrategy.AUTO_INHERIT_FROM_CONFIG, unmappedSourcePolicy = ReportingPolicy.ERROR, unmappedTargetPolicy = ReportingPolicy.ERROR) public interface ParentMapperConfig { @Mapping(target = "idDto", source = "id") ParentDto map(Parent parent); @Mapping(target = "id", source = "idDto) Parent map(ParentDto parentDto); }

and the mapper as:

@Mapper(config = ParentMapperConfig.class) public interface ParentToParentDto { ParentDto map(Parent parent); Parent map(ParentDto parentDto); }

My impl looks correct with the correct mappings for id<->idDto.

When I create the ChildToChildDto mapper I would prefer not to have to repeat the id<->idDto mappings but I cannot figure out how to accomplish that. I have tried:

@MapperConfig(uses = ParentMapperConfig.class) public interface ChildMapperConfig { @Mapping(target = "nickNameDto", source = "nickName") ChildDto map(Child child); @Mapping(target = "nickName", source = "nickNameDto) Child map(ChildDto childDto); }

and the mapper as:

@Mapper(config = ChildMapperConfig.class) public interface ChildToChildDto { ChildDto map(Child child); Child map(ChildDto childDto); }

as well as quite a number of other incantations. Unfortunately, the ChildToChildDto does not pick up the id<->idDto mapping from the parent. This seems like it should be a solved problem but I cannot find a solution. Any advice/pointers would be greatly appreciated. Thanks.

Read Entire Article