【问题标题】:Mapstruct: one source field to several multiple target fieldsMapstruct:一个源字段到几个多个目标字段
【发布时间】:2021-12-03 15:42:44
【问题描述】:
public class ExtensionTarget {

    private StringType valueString;
    private BooleanType valueBoolean;
    private CodeableConcept valueCodeableConcept;
    
}

public class ExtensionSource {

    private Type value;
    
}

其中StringTypeBooleanTypeCodeableConcept 继承自Type

目前,我正在使用这个映射器来制作这个映射:

@Mapper(
    uses = { TypeMapper.class }
)
public interface ExtensionMapper {

    ExtensionTarget fhirToMpi(ExtensionSource fhirType);
}

public abstract class TypeMapper {
    
    private final StringTypeMapper stringTypeMapper = Mappers.getMapper(StringTypeMapper.class);
    private final BooleanTypeMapper booleanTypeMapper = Mappers.getMapper(BooleanTypeMapper.class);
    private final CodeableConceptMapper codeableConceptMapper = Mappers.getMapper(CodeableConceptMapper.class);

    public Type fhirToMpi(org.hl7.fhir.r4.model.Type fhirType) {
        if (fhirType instanceof CodeableConcept) {
            return this.codeableConceptMapper.fhirToMpi((CodeableConcept)fhirType);
        } else if (fhirType instanceof StringType) {
            return this.stringTypeMapper.fhirToMpi((StringType)fhirType);
        } else if (fhirType instanceof BooleanType) {
            return this.booleanTypeMapper.fhirToMpi((BooleanType)fhirType);
        }
        return null;
    }

}

还有其他更优雅的获取方式吗?

【问题讨论】:

    标签: mapstruct


    【解决方案1】:

    目前没有优雅的方式来实现您正在寻找的东西。但是,很快,就像很快我们将发布 MapStruct 1.5.Beta2 一样,您的请求将作为this PR 的一部分实现。

    简而言之,一旦 1.5.Beta2 发布,您可以执行以下操作:

    @Mapper(uses = {
            StringTypeMapper.class,
            BooleanTypeMapper.class,
            CodeableConceptMapper.class,
        })
    public interface TypeMapper {
        
    
        @SubclassMapping(target = CodeableConcept.class, source = org.hl7.fhir.r4.model.CodeableConcept.class)
        @SubclassMapping(target = StringType.class, source = org.hl7.fhir.r4.model.StringType.class)
        @SubclassMapping(target = BooleanType.class, source = org.hl7.fhir.r4.model.BooleanType.class)
        Type fhirToMpi(org.hl7.fhir.r4.model.Type fhirType);
    }
    

    我假设您的子类与您的源类型在同一个包中。 除此之外,还有SubclassExhaustiveStrategy 可以控制未定义类型之间的映射应该如何发生。

    即如果目标类型没有有效的构造函数或者它是抽象的。 目前的可能性是:

    • COMPILE_ERROR - 如果您尝试这样做,基本上就是现在发生的情况
    • RUNTIME_EXCEPTION - 将抛出一个运行时IllegalArgumentException

    在您的示例中,您返回null。这也是一个有效的选项。如果需要,我建议您在 MapStruct 跟踪器中创建一个问题以添加此功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-20
      • 2018-08-07
      • 2019-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多