Storing Enum Values with JPA

不羁岁月 提交于 2020-02-02 04:23:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!