如何扩展mapstruct的@映射注释



我有一个字典,它有多个字段,如:idcoderuNameenNameid是UUID,其他是Strings。

我想要的是这样的东西:

@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);

并有一个名为Dictionary的单独类,在其中存储映射以供检索。通过这种方式,您可以很容易地将Dictionary替换为另一个Dictionary实现,以防需要不同的翻译。

Dictionary类示例:

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);
}

最新更新