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

annotations, enums, hibernate

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.

Problem

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)`, 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. Kindly suggest a solution.

Original source