I have a Enum with three values. It's being used as a property in an Entity bean.
Here's the property in the bean:
@Enumerated(EnumType.ORDINAL)
private BillingMethod billingMethod;
Here's the enum class:
public enum BillingMethod {
ONLINEBILL("enum.billingmethod.onlinebill"), // Should be 1, but is now 0 in the database
PAPERBILL("enum.billingmethod.paperbill"), // Should be 2, but is now 1 in the database
PRINT("enum.billingmethod.print"); // Should be 3, but is now 2 in the database
private String tag;
private BillingMethod(String tag){
this.tag = tag;
}
@Override
public String getTag() {
return tag;
}
}
There is a very rare, specific reason why I need those values to be 1, 2, 3. Instead of the usual 0, 1, 2 in the database.
Don't worry about the tag
here, it is used to get the String presentation from a property file.
So, how can I set the ORDINAL to begin from 1 instead of 0?
I see two options :
The easiest: map an Integer for hibernate, do the decoding to an enum in the getter :
The issue is that searching with hql or criteria will not work without doing this same encoding / decoding. Not really great.
Create a custom UserType. More info in the reference documentation
Then map the field this way :
(when using the fully qualified name of the user type in the
@Type
annotation, you don't need to register it)A bit more complex to implement, but will work in every situations where a standard enum mapping would have worked