Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Hibernate annotations to persist custom value for Enumerated attribute

I have lots of Java enums that I persist with Hibernate. As far as I know there are two different standard ways to persist these enums:

@Enumerated(EnumType.ORDINAL)

This is the default, and it just persists the ordinal value from the enum.

@Enumerated(EnumType.STRING)

This persists the name of the enum value.

Those have worked fine for me so far, but now I have a new enum where I want to persist a custom value from the enum that is neither the ordinal nor the name. Is this possible? I searched around and saw lots of people asking how to persist the name, which is easily accomplished using EnumType.STRING, but I want to persist an int that can be used for comparison in my SQL queries. I tried overriding toString() to return my custom value, but that did not work.

I'll paste my java enum below. I want to persist the int value member from the enum.

Thanks in advance!

public enum Permission {
    VIEW (4),
    CHANGE(6),
    FULL(7);

    private int value;

    Permission(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}
like image 208
Ike Walker Avatar asked Feb 17 '11 17:02

Ike Walker


1 Answers

You can implement a UserType with desired behaviour and configure Hibernate to use it with @Type annotation.

See, for example, UserType for persisting a Typesafe Enumeration with a VARCHAR column .

like image 141
axtavt Avatar answered Oct 06 '22 19:10

axtavt