使用 JPA 存储枚举值

Gre*_*egg 5 java enums spring hibernate jpa

说我有一个枚举:

public enum NotificationType {

    Store("S"),
    Employee("E"),
    Department("D"),
    All("A");

    public String value;

    NotificationType(String value) {
        this.value = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想在数据库中存储SorE而不是Storeor Employee。目前,我已将其映射到实体中,如下所示:

@Enumerated(EnumType.STRING)
private NotificationType notificationType;
Run Code Online (Sandbox Code Playgroud)

但如果可能的话,不确定如何得到我想要的东西。

Ale*_*rov 5

您可以声明自己的用户类型来进行字符串和枚举之间的转换,您可以在本文中找到更多信息:

http://javadata.blogspot.no/2011/07/hibernate-and-enum-handling.html

一个小注释 UserType 是 Hibernate 特定的。如果您只想使用 JPA。您需要属性转换器。您可以在这里找到如何做到这一点:

http://www.thoughts-on-java.org/jpa-21-type-converter-better-way-to/

Stackoverflow 上处理属性转换器的另一个链接显示了这种转换器的确切实现。 是否可以为 JPA 编写通用枚举转换器?