How to use Enums in Hibernate Persistence

Points To Remember


  • Enums are special java classes that are used to declare constants and methods.
  • Enums have all the variables declared as public static final.
  • Enums variables can be compared using == operator.
  • End of a enum can be declared by a semi colon, but this is optional.
  • There are two ways to use Enums 
    • ORDINAL (saves the enum values in integer format starting from 0.)
    • STRING (saves the enum value in String, takes the value of the field itself. )

Use Enums in Hibernate

In this example we will be using Enums to save a value in database using hibernate.
Suppose we have a Enum named Level and we want to save it in database using hibernate persistence.Then we can map this in the following way.

Level.java
This is an Enum that defines the level of difficulty of a question.
package com.ekiras.enums;

public enum Level {

 LEVEL_ONE,
 LEVEL_TWO,
 LEVEL_THREE,
 LEVEL_FOUR,
 LEVEL_FIVE;
}

Qusetion.java
This class contains the enum as a field that will be saved to the database.
package com.ekiras.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import com.ekiras.enums.Level;

@Entity
@Table(name="question")
public class Question {
  
        @Id
        @Column(name="id")
        @GeneratedValue(strategy=GenerationType.AUTO)
        private Long id;

        @Column(name="question")
        private String question;

        @Column(name="level")
        @Enumerated(EnumType.ORDINAL)
        private Level status = Level.LEVEL_ONE;
  
        // GETTERS and SETTERS

}
This will save the Enum in integer format, i.e it will save the int value of the enum. If you want to save the value in String format you need to add the following Enumerated property to the field.

        
 @Column(name="level")
 @Enumerated(EnumType.STRING)
 private Level status = Level.LEVEL_ONE;

This will save the value of the field in String format, i.e it will save LEVEL_ONE in database while @Enumerated(EnumType.ORDINAL) will save the values in integer format i.e it will save integer values for LEVEL_ONE  = 0 and so on(it has nothing to do with the value of the enum, it always starts from zero and increments and is defined by the order in which they are defined. ).


No comments :

Post a Comment