我有一个枚举:
public enum NotificationType {
OPEN("open"),
CLOSED("closed");
public String value;
NotificationType(String value) {
this.value = value;
}
}
我想将自定义字符串
open
或closed
而不是OPEN
或CLOSED
传递给实体。目前,我已将其映射到实体中,如下所示:@Enumerated(EnumType.STRING)
private NotificationType notificationType;
哪种方法是存储/获取枚举值的最佳方法?
最佳答案
您可以像这样创建自定义converter:
@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);
}
}
也许您需要从
notificationType
字段中删除注释,以便此转换器生效。