MapStruct有没有一种在类级别定义未知值的默认枚举策略的方法?

huangapple go评论74阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年9月9日 05:52:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/63802034.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定