如何使用 MapStruct 实现部分自定义映射?
How to implement a partial custom mapping with MapStruct?
我希望 MapStruct 映射我的对象的每个 属性,除了一个我想为其提供自定义映射的特定对象。
到目前为止,我自己实现了整个映射器,但是每次向我的实体添加新的 属性 时,我都忘记更新映射器。
@Mapper(componentModel = "cdi")
public interface MyMapper {
MyMapper INSTANCE = Mappers.getMapper(MyMapper.class);
default MyDto toDTO(MyEntity myEntity){
MyDto dto = new MyDto();
dto.field1 = myEntity.field1;
// [...]
dto.fieldN = myEntity.fieldN;
// Custom mapping here resulting in a Map<> map
dto.fieldRequiringCustomMapping = map;
}
}
有没有办法外包我的字段 fieldRequiringCustomMapping 的映射并告诉 MapStruct 像往常一样映射所有其他字段?
MapStruct 有一种方法可以在某些字段之间使用自定义映射。因此,在您的情况下,您可以执行以下操作:
@Mapper(componentModel = "cdi")
public interface MyMapper {
@Mapping(target = "fieldRequiringCustomMapping", qualifiedByName = "customFieldMapping")
MyDto toDTO(MyEntity myEntity);
// The @(org.mapstruct.)Named is only needed if the Return and Target type are not unique
@Named("customFieldMapping")
default FieldRequiringCustomMapping customMapping(SourceForFieldRequiringCustomMapping source) {
// Custom mapping here resulting in a Map<> map
return map
}
}
我不知道你的 fieldRequiringCustomMapping
需要映射什么,这个例子假设你在 MyEntity
中也有这样的字段,如果不是这样你就需要将 source
添加到 @Mapping
.
旁注:在您的情况下使用非默认 componentModel
时 cdi
不建议使用 Mappers
工厂。如果您在映射器中使用它们,它不会执行其他映射器的注入。
我希望 MapStruct 映射我的对象的每个 属性,除了一个我想为其提供自定义映射的特定对象。
到目前为止,我自己实现了整个映射器,但是每次向我的实体添加新的 属性 时,我都忘记更新映射器。
@Mapper(componentModel = "cdi")
public interface MyMapper {
MyMapper INSTANCE = Mappers.getMapper(MyMapper.class);
default MyDto toDTO(MyEntity myEntity){
MyDto dto = new MyDto();
dto.field1 = myEntity.field1;
// [...]
dto.fieldN = myEntity.fieldN;
// Custom mapping here resulting in a Map<> map
dto.fieldRequiringCustomMapping = map;
}
}
有没有办法外包我的字段 fieldRequiringCustomMapping 的映射并告诉 MapStruct 像往常一样映射所有其他字段?
MapStruct 有一种方法可以在某些字段之间使用自定义映射。因此,在您的情况下,您可以执行以下操作:
@Mapper(componentModel = "cdi")
public interface MyMapper {
@Mapping(target = "fieldRequiringCustomMapping", qualifiedByName = "customFieldMapping")
MyDto toDTO(MyEntity myEntity);
// The @(org.mapstruct.)Named is only needed if the Return and Target type are not unique
@Named("customFieldMapping")
default FieldRequiringCustomMapping customMapping(SourceForFieldRequiringCustomMapping source) {
// Custom mapping here resulting in a Map<> map
return map
}
}
我不知道你的 fieldRequiringCustomMapping
需要映射什么,这个例子假设你在 MyEntity
中也有这样的字段,如果不是这样你就需要将 source
添加到 @Mapping
.
旁注:在您的情况下使用非默认 componentModel
时 cdi
不建议使用 Mappers
工厂。如果您在映射器中使用它们,它不会执行其他映射器的注入。