问题
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.
回答1:
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?
来源:https://stackoverflow.com/questions/38252617/storing-enum-values-with-jpa