Blankman
Blankman

Reputation: 267140

Can you save enums using an integer value instead of the EnumType.STRING or ORDINAL?

I have a mysql table that I am storing the enumeration string value in.

My model has the annotation:

@Enumerated(EnumType.STRING)

My enum looks like:

public enum SomeEnum {

   BLUE(0),
   YELLOW(1),
   RED(2),

   private int value;

   public SomeEnum(int value) {
     this.value = value;
   }

}

I was hoping I could somehow store the integer 'value' of the enum in my database, and then somehow parse it back using the value to the enum again when hibernate loads my model into a java class.

I don't want to use the ordinal value as that isn't stable enough. And I don't want to use the mysql enum type either as it ties me into mysql for no good reason.

So is this possible?

Upvotes: 0

Views: 2570

Answers (3)

wholenewstrain
wholenewstrain

Reputation: 319

Seems like it is possible. Tried that tip from: http://blog.tamashumi.com/2013/06/grails-enum-custom-database-value.html And seems to be working:

enum DayTime {
    Morning(0),Noon(1),AfterNoon(2),Night(3)
    final int id
    private DayTime(int id) { this.id = id }
}

Then in your domain class:

DayTime dayTime

Upvotes: 0

MykoB
MykoB

Reputation: 184

Why don't you try with a field which is int type (not enumerated) and if you want you just get/set it from the Enum type you have?

Upvotes: 2

barsju
barsju

Reputation: 4446

I guess you could always map your own user type: http://alenovarini.wikidot.com/mapping-a-custom-type-in-hibernate

Upvotes: 2

Related Questions