Хранение пользовательских значений Enum с помощью JPA - PullRequest
4 голосов
/ 03 марта 2020

У меня есть enum:

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;

Какой лучший способ сохранить / извлечь значение перечисления?

Ответы [ 2 ]

5 голосов
/ 03 марта 2020

Вы можете создать собственный конвертер следующим образом:

@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, чтобы этот конвертер вступил в силу.

0 голосов
/ 03 марта 2020

Да, в основном вам нужно разработать специальный конвертер для этого, но я предлагаю вам использовать Необязательно , чтобы избежать работы с null и exceptions.

Добавить в NotificationType :

public static Optional<NotificationType> getFromValue(String value) {
   return Optional.ofNullable(value)
                  .flatMap(dv -> Arrays.stream(NotificationType.values())
                                    .filter(ev -> dv.equals(ev.value))
                                    .findFirst());
}

Создайте необходимый конвертер:

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;    

@Converter(autoApply = true)
public class NotificationTypeConverter implements AttributeConverter<NotificationType, String> {

   @Override
   public String convertToDatabaseColumn(NotificationType notificationType) {
      return null == notificationType ? null : notificationType.value;
   }

   @Override
   public NotificationType convertToEntityAttribute(String databaseValue) {
      return NotificationType.getFromValue(databaseValue)
                             .orElse(null);
   }
 }

И теперь вам нужно только изменить свою модель:

@Entity
@Table
public class MyEntity {

   @Convert(converter=NotificationTypeConverter.class)
   private NotificationType notificationType;
}  
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...