2

This is my enum :

package enums;

public enum SessionType {
    SESSION_NORMAL(12), SESSION_PERFECT(5), SESSION_SOLO(1);

    private int value;

    private SessionType(int value) {
        this.setValue(value);
    }

    public void setValue(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public String toString(){
        return this.name();
    }

}

I've got a models class Session with an attribut type :

@Required
@Enumerated(EnumType.STRING)
@Column(name="type")
private SessionType type;

And I would like to do a query like that :

Session.find("type.value = 1");

Regards.

Jonas
  • 121,568
  • 97
  • 310
  • 388
Falydoor
  • 462
  • 6
  • 19

2 Answers2

1

By default the enum name is stored in the DB, unless you have some wrapper or something that saves the actual value.

Therefore you query should be something like the following:

Session.find("type='SESSION_SOLO'");
Garytxo
  • 346
  • 1
  • 4
  • 11
  • Ok thx, so i can't do numerical condition like : Session.find("type.value - 5 > 0"); I will create a table with the value of the enum so. – Falydoor Jun 07 '11 at 09:35
  • unfortunately you cannot do that type of query. check this post out they have a solution for what you are after: http://stackoverflow.com/questions/2751733/map-enum-in-jpa-with-fixed-values – Garytxo Jun 07 '11 at 10:11
  • Pere: Using the ordinal value could cause problems, espcially if someone was to change the order of the enums in the code? Similar to the name, if someone changes the name of an enum and the database is no updated there could be serious consequences. – Garytxo Jun 07 '11 at 13:18
1

You can't access the value inside the enum via a SQL query, but you could just use the Ordinal value of the enumeration to store this in the database with the annotation:

@Enumerated(EnumType.ORDINAL)

That would return 1, 2 or 3 right now, but you can either remap the values (so instead of 1,5,12 you use 1,2,3) or simply add some extra entries to the enumeration until you get the values yo want (if it's so important for the rest of the system that the values are 1,5,12)

Pere Villega
  • 16,429
  • 5
  • 63
  • 100