Hibernate and Enumeration
Enumeration is widely used in model classes.Hibernate has inbuilt support for non parameterized enumeration.However for parameterized enumeration,we have to provide an User Type implementation implementing UserType and Parameterized Type.
Plain Enumeration in Hibernate
Lets take a simple case of plain enumeration.Here we are creating a non parameterized enumeration for educational qualification and using it in the model class.
EduEnum.java having enumeration values for High School,Under Graduate,Post Graduate and PhD
If we have to use such plain enums in Hibernate,we just have to define @Enumerated annotation on the corresponding field.
We are going to use EduEnum in PersonEduEnum.java
PersonEduQual.java -In this class we have eduQual property mapped to EduEnum.In order to tell the hibernate that property is mapped to an enumeration.We just have to provide @Enumerated annotation
So using plain enumeration is very simple.By providing the @Enumerated annotation,hibernate knows that it has to fetch the value from enumeration and to create an enumeration when fetching the information from database.Internally Hibernate uses an user type for doing this.
Paramterized Enumeration in Hibernate
There are some cases when we have to show different information in the UI and persist different information in the database.In that case we use parameterized enumeration.
Lets take the use case of Gender.We want to show MALE in the UI.But persist it as 'M' in the database.Similarly for FEMALE,we want to persist it as 'F' in database.Inorder to support it we create a parameterized user type.
GenderEnum.java- Implementation of Parameterized enumeration
Here we are storing MALE as 'M' and FEMALE as 'F'
EnumUserType.java-Parameterized user type for handling parameterized enum.In this user type,we pass some parameters which we use in user type for doing parameterized enumeration conversion.
In this UserType,we pass parameters like method to create enumeration,method to fetch value to persist in database and actual enumeration class which needs to be looked up for method implementations
In order to use the paramterized enum and corresponding usertype in the class.We define the user type and pass the paramters.In the EnumPerson class look at the genderEnum property where we are providing this mapping.
EnumPerson.java using the paramterized enum for genderEnum property.