hibernate - How to annotate a property as enum with a field
How do I map an enum with a field in it?
public enum MyEnum{
HIGHSCHOOL ("H"), COLLEGE("C")
private int value;
public MyEnum getInstance(String value){...}
}
@Entity
public class MyEntity {
@Enumerated(...)
private MyEnum eduType;
}
How do I annotate so that values H, C will be persisted in the database? If I keep @Enumerated(EnumType.STRING)
, H开发者_如何学编程IGHSCHOOL instead of H will be stored in the database. If I use EnumType.ORDINAL
, 1 instead of H will be stored in the database. Kindly suggest a solution.
There's no built-in way to do this in Hibernate. You can write a UserType to do that for you if you want.
This is a good start, but you'll need to replace nullSafeSet()
and nullSafeGet()
implementations to store your enum code (e.g. 'H' / 'C' / what have you) and return proper enum instance based on it.
If you have more than one enum type you need to do this for, you can implement ParameterizedType interface to pass enum type as parameter or use reflection to retrieve the "code" as long as accessor methods are named consistently.
Thank you ChssPly76 for the solution. I implemented a user type and it works well. In fact, there is an example in the hibernate community to persist the value/token in the enum. Click here: StringValuedEnum
精彩评论