If you try to fetch an undefined enum ordinal value in JPA backed by Hibernate,
you will get the following exception:
java.lang.IllegalArgumentException: Unknown ordinal value [100] for enum class [com.izeye.test.event.domain.EventSource]
at org.hibernate.type.EnumType$OrdinalEnumValueMapper.fromOrdinal(EnumType.java:391)
at org.hibernate.type.EnumType$OrdinalEnumValueMapper.getValue(EnumType.java:381)
at org.hibernate.type.EnumType.nullSafeGet(EnumType.java:107)
at org.hibernate.type.CustomType.nullSafeGet(CustomType.java:127)
at org.hibernate.type.AbstractType.hydrate(AbstractType.java:106)
at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2969)
at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1696)
If you want to avoid the above exception and just get `null` instead,
add the following code:
@Converter(autoApply = true)
public class EventSourceConverter implements AttributeConverter<EventSource, Integer> {
@Override
public Integer convertToDatabaseColumn(EventSource eventSource) {
return eventSource.ordinal();
}
@Override
public EventSource convertToEntityAttribute(Integer ordinal) {
EventSource[] values = EventSource.values();
if (ordinal >= values.length) {
return null;
}
return values[ordinal];
}
}
Reference:
http://www.javacodegeeks.com/2014/05/jpa-2-1-type-converter-the-better-way-to-persist-enums.html
No comments:
Post a Comment