Да, в основном вам нужно разработать специальный конвертер для этого, но я предлагаю вам использовать Необязательно , чтобы избежать работы с 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;
}