Say I have an enum:
public enum NotificationType {
Store("S"),
Employee("E"),
Department("D"),
All("A");
public String value;
NotificationType(String value) {
this.value = value;
}
}
I want to store S
or E
rather than Store
or Employee
in the database. Currently, I've mapped it in the entity as follows:
@Enumerated(EnumType.STRING)
private NotificationType notificationType;
but unsure how to get what I want, if possible.
Storing the Raw Value It isn't possible to store an enum in the user's defaults database. We need to convert the value to a type that is supported by the defaults system. The easiest solution is to ask the enum for its raw value and store that value in the user's defaults database.
If you are using JPA 2.1 you have the option to use the new @Convert annotation. This requires the creation of a converter class, annotated with @Converter, inside which you would define what values are saved into the database for each enum type. Within your entity you would then annotate your enum with @Convert.
Ordinal. Ordinal is the default type. This will map only the index of Enum which is taken from the order of enum list. So, the enum value that's defined first gets mapped to 0, the second one to 1, and so on.
You can declare own user type to do the conversion between the strings and the enum you can find out more in this article:
http://javadata.blogspot.no/2011/07/hibernate-and-enum-handling.html
One small remark UserType is Hibernate specific. If you want to use JPA only. You need attribute converter. How to do that you can find here:
http://www.thoughts-on-java.org/jpa-21-type-converter-better-way-to/
And one more link on Stackoverflow dealing with Atribute converters shows exact implementation of such. Is it possible to write a generic enum converter for JPA?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With