13

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.

Alexander Petrov
  • 9,204
  • 31
  • 70
Gregg
  • 34,973
  • 19
  • 109
  • 214
  • 3
    Just want to note, your enum is mutable, it's recommended to make enum fields `final`. And consider declaring the field `value` as `private` with `public` getter. – Vladimir Vagaytsev Jul 07 '16 at 18:24

1 Answers1

5

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?

Community
  • 1
  • 1
Alexander Petrov
  • 9,204
  • 31
  • 70