Mapstruct - generate mappers for all classes inherited from a base class?

Viewed 48

I have a Mapstruct mapper which I use to merge incoming requests with existing data - the mapper looks like this

@Mapper(uses = ProtoMapperUtil.class,
    collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED,
    unmappedTargetPolicy = ReportingPolicy.IGNORE,
    nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS)
public interface FooEntityMapper extends BaseMapper<FooEntity> {
    FooEntityMapper INSTANCE = Mappers.getMapper(FooEntityMapper.class);
}

The BaseMapper looks like this

public interface BaseMapper<T extends BaseEntity> {
    T merge(T var1, @MappingTarget T var2);
}

Considering that I have multiple entities like FooEntity and all of them extend BaseEntity, I have to define a mapper manually for each of these entities - something that I don't really need to do because the functionality doesn't change across classes. Is there a way to define the Mapstruct properties on a global level (?) so that it automatically generates a mapper for every bean that extends from BaseEntity?

1 Answers

As you, I used BaseEntity on my older project. This is how I configured the mappers.

public interface BaseMapper {

    BaseEntity toBaseEntity(BaseDTO baseDTO);
  
    BaseDTO toBaseDTO(BaseEntity baseEntity);

}    

on the foo Mapper you have to add the BaseMapper as config.

@Mapper(
    config = BaseMapper.class,
    uses = { ProtoMapperUtil.class,
             collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED,
             unmappedTargetPolicy = ReportingPolicy.IGNORE,
             nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS})
public interface FooEntityMapper {

    FooEntityMapper INSTANCE = Mappers.getMapper(FooEntityMapper.class);

    //I don't remember if you need or not to declare the @InheritConfiguration
    //@InheritConfiguration(name = "toBaseDTO")
    FooDTO toFooDTO(FooEntity fooEntity)

}
Related