使用 JPA 存储枚举自定义值

Van*_*a V 4 java spring jpa

我有一个枚举:

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)

哪个是存储/获取枚举值的最佳方式?

Kar*_*tik 5

您可以像这样创建自定义转换器

@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字段中删除注释,以便此转换器生效。

  • @Glains是的,我会将其移至枚举本身的一个方法,该方法将采用一个字符串并返回枚举 (2认同)