[英]Hibernate how to map Enum key and value in Map<enum,enum> as a String
[英]Map enum to string value
我正在使用最新版本的MapStruct
。 我正在尝试将相应字符串值的值映射到实际的enum
值。
例如,这是我的enum
:
@Getter
@RequiredArgsConstructor
@Accessors(fluent = true)
public enum Type {
T1("SomeValue"),
T2("AnotherValue");
private final String label;
}
我有一个Java
类型( ForeignType
),其字段/成员接收数据( enum
中的字符串值之一): SomeValue
或AnotherValue
。 然后我有一个“受控”类型( MyType
),我想在这个类型中使用实际的枚举常量( T1
或T2
),基于发送的字符串值。
我正在寻找一种使用MapStruct
来执行此操作的方法,因为该应用程序当前将它用于所有映射目的,但到目前为止我找不到实现此目的的方法。
MapStruct 具有@ValueMapping
的概念,可用于将 String 映射到Enum
。
例如
@Mapper
public interface TypeMapper {
@ValueMapping(target = "T1", source = "SomeValue")
@ValueMapping(target = "T2", source = "AnotherValue")
Type map(String type);
}
执行上述 MapStruct 将为您实现一个方法。 但是,另一种方法是使用自定义方法进行映射:
例如
public interface TypeMapper {
default Type map(String type) {
if (type == null) {
return null;
}
for(Type t: Type.values()) {
if (type.equals(t.label()) {
return t;
}
}
throw new IllegalArgumentException("Cannot map label " + type + " to type");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.