Storing Enum in Hibernate 4

I recently faced a conundrum in that I wanted to use an enum to represent a value saved through Hibernate to a database. I didn’t want to store the name of the enum, rather a discriminator bound as a property of the enum. For example:

public enum Status {
    TOP_PRIORITY("Top Priority", 1), MIDDLE("Important", 2),
    LOW_PRIORITY("Low", 3), NONE("None", 4);

    private String display;
    private int value;

    Status(String display, int value) {
        this.display = display;
        this.value = value;
    }

    public String getDisplay() {
        return display;
    }

    public int getValue() {
        return value;
    }
}

In this situation, I want the status stored as an INT. To do so, you may find online references of using the Hibernate annotation @Enumerated(EnumType.String) or @Enumerated(EnumType.Ordinal). You may also see an implementation of the UserType interface. I decided for a more… simple solution.

Instead of those, I create the following:

@Entity
@Table("tasks")
public class Task {
    // ID and other fields omitted

    @Column(name = "status", nullable = false)
    private int statusValue;

    @Transient
    private Status status;

    // getters & setters omitted

    // When setting the statusValue, set the Status
    public void setStatusValue(int statusValue) {
        this.statusValue = statusValue;
        this.status = Status.getFromIntValue(statusValue);
    }

    // when setting the status, set the statusValue
    public void setStatus(Status status) {
        this.status = status;
        if (status != null) {
            statusValue = status.getValue();
        }
    }
}

The final piece is to write a function in my Status enum to get a Status based on the int value.

In conclusion, rather than a larger process, just add a separate, transient attribute to hold the Status, and store it as the value.

Leave a Reply

Your email address will not be published. Required fields are marked *