我有一个枚举:
public enum NotificationType {
OPEN("open"),
CLOSED("closed");
public String value;
NotificationType(String value) {
this.value = value;
}
}
Run Code Online (Sandbox Code Playgroud)
我想将自定义字符串openorclosed而不是OPENorCLOSED传递给实体。目前,我已将其映射到实体中,如下所示:
@Enumerated(EnumType.STRING)
private NotificationType notificationType;
Run Code Online (Sandbox Code Playgroud)
哪个是存储/获取枚举值的最佳方式?
您可以像这样创建自定义转换器:
@Converter(autoApply = true)
public class NotificationTypeConverter implements AttributeConverter<NotificationType, String> {
@Override
public String convertToDatabaseColumn(NotificationType notificationType) {
return notificationType == null
? null
: notificationType.value;
}
@Override
public NotificationType convertToEntityAttribute(String code) {
if (code == null || code.isEmpty()) {
return null;
}
return Arrays.stream(NotificationType.values())
.filter(c -> c.value.equals(code))
.findAny()
.orElseThrow(IllegalArgumentException::new);
}
}
Run Code Online (Sandbox Code Playgroud)
也许您需要从您的notificationType字段中删除注释,以便此转换器生效。
| 归档时间: |
|
| 查看次数: |
233 次 |
| 最近记录: |