簡體   English   中英

如何擴展 mapstruct 的 @mapping 注釋

[英]How to extend mapstruct`s @mapping annotation

我有一個字典,它有多個字段,如: idcoderuNameenName id是一個 UUID,其他是String s。

我想要的是這樣的:

@Mapping(source = "sourceName", target = "targetName", dictionary = "dictName", dictionaryField = "dictionaryField")

並根據目標類型生成類似的東西

if target type UUID 
    return target.targetName(getId(dictionary ,dictionaryField , sourceName));

if target type String
    return target.targetName(getValue(dictionary, dictionaryField, sourceName));

我現在擁有的是一個生成器,它為每個字典和格式為dictionaryByFieldName的每個字段生成映射器,所以我可以使用這種格式:

@Mapping(source="sourceName", target="targetName", qualifiedByName = "dictionaryByFieldName")

但我不喜歡它,因為大多數創建的映射器在項目中沒有用處並且不是有效的,因為並非每個字段都是唯一的,無法按字段獲取 ID-_-

目前無法在 mapstruct 中檢索字段名,但是可以使用每個字段的@Mapping來最小化映射代碼量。

例如:

    @Mapping( target = "myUuidFieldName", expression = 'java(dict.getId("myUuidFieldName", source.getMyUuidFieldName()))' )
    @Mapping( target = "myStringFieldName", expression = 'java(dict.getValue("myStringFieldName", source.getMyStringFieldName()))' )
    Target map(Source source, @Context Dictionary dict);

並有一個單獨的 class 稱為Dictionary ,您可以在其中存儲用於檢索的映射。 通過這種方式,您可以輕松地將Dictionary替換為另一個Dictionary實現,以防您需要不同的翻譯。

Dictionary示例 class:

private class Dictionary{
    DbRecordAccessor dbRecord;
    Map<String, RetrievalInformation> retrievalMap;
    // constructor and retrievalMap initialization methods

    UUID getId(String fieldName, String value){
        RetrievalInformation info = retrievalMap.get(fieldName);
        return dbRecord.getId(info.getDictionaryName(), fieldName, info.getDictionaryField());
    }

    String getValue(String fieldName, String value){
        RetrievalInformation info = retrievalMap.get(fieldName);
        return dbRecord.getValue(info.getDictionaryName(), fieldName, getId(fieldName, value));
    }
}

mapstruct(還)不支持以下內容。 瀏覽此處獲取更多信息。

如果您可以執行以下操作,那就太好了:

    Target map(Source source, @Context Dictionary dict);

    UUID getId(String value, @TargetProperty String targetField, @Context Dictionary dict) {
        return dict.getId(targetField, value);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM