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;
}
}
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 .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With