Hibernate - How to annotate a property as enum with a field

How do I display an enumeration 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 to annotate so that the values ​​of H, C are stored in the database? If I save @Enumerated(EnumType.STRING) , HIGHSCHOOL instead of H will be stored in the database. If I use EnumType.ORDINAL , 1 instead of H will be stored in the database. Please suggest a solution.

+4
source share
2 answers

Hibernate has no built-in way to do this. You can write UserType to do this for you if you want.

This is a good start, but you will need to replace the nullSafeSet() and nullSafeGet() implementations to store your enumeration code (for example, "H" / "C" / what you have) and return the correct enum instance to it.

If you have several types of enumerations, for which you need to do this, you can implement the ParameterizedType interface to pass the enumeration type as a parameter or use reflection to get "code" if access methods are called sequentially.

+3
source

Thanks to ChssPly76 for the solution. I applied a user type and it works well. In fact, there is an example in the hibernation community to store a value / token in an enumeration. Click here: StringValuedEnum

0
source

All Articles