gpt4 book ai didi

java - 使用 JPA 存储枚举自定义值

转载 作者:行者123 更新时间:2023-12-01 12:55:41 24 4
gpt4 key购买 nike

我有一个枚举:

public enum NotificationType {

OPEN("open"),
CLOSED("closed");

public String value;

NotificationType(String value) {
this.value = value;
}
}

我想传递自定义字符串 openclosed而不是 OPENCLOSED到实体。目前,我已将其映射到实体中,如下所示:
@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 中删除注释。字段,以便此转换器生效。

关于java - 使用 JPA 存储枚举自定义值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60500739/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com