英文:
MapStruct Is there a way to define defaut enum strategy for unknown value at class level?
问题
我正在寻找在映射器类级别上定义一种策略,即如果枚举值未映射,则将其映射为 null。
就像我在方法级别上写的那样:
@ValueMapping(source = MappingConstants.ANY_REMAINING, target = MappingConstants.NULL)
这样可以自动应用于由 MapStruct 自动生成的所有子映射方法,而无需强制我声明所有这些方法只是为了添加这行代码。
英文:
I'm looking to define at mapper class level, a strategy that said if an enum value is not mapped, to map it to null.
Just like i would write at method level:
@ValueMapping( source = MappingConstants.ANY_REMAINING, target = MappingConstants.NULL )
So that it applies to all sub mapping method automaticaly generated by mapstruct, without forcing me to declare all of them just to add this line.
答案1
得分: 2
创建一个用于枚举的 'class' 映射器,并在其他映射器中使用 @Mapper
注解的 uses
属性。
例如:
public interface MyEnumMapper {
@ValueMapping( source = MappingConstants.ANY_REMAINING, target = MappingConstants.NULL )
public String asString(MyEnum myenum);
}
然后在其他映射器中使用它:
@Mapper(uses=MyEnumMapper.class)
public class CarMapper {
CarDto carToCarDto(Car car);
}
(假设 Car
对象具有类型为 MyEnum
的属性)
详细文档请参阅:https://mapstruct.org/documentation/stable/reference/html/#invoking-other-mappers
英文:
Create a 'class' mapper for your enum and then use it in other mapper with the uses
attribute of the @Mapper
annotation.
For example :
public interface MyEnumMapper {
@ValueMapping( source = MappingConstants.ANY_REMAINING, target = MappingConstants.NULL )
public String asString(MyEnum myenum);
}
and then to use it
@Mapper(uses=MyEnumMapper.class)
public class CarMapper {
CarDto carToCarDto(Car car);
}
(assuming Car
object has an attribute of type MyEnum
)
see the full documentation here : https://mapstruct.org/documentation/stable/reference/html/#invoking-other-mappers
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论