Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing Enum Values with JPA

Tags:

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.

like image 289
Gregg Avatar asked Jul 07 '16 18:07

Gregg


People also ask

How are enum values stored?

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.

How does JPA define enum?

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.

What is the default enum value type in JPA?

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.


1 Answers

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?

like image 133
Alexander Petrov Avatar answered Sep 28 '22 02:09

Alexander Petrov