Play! JPA - Get an enum value in a query
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.
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)
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'");
精彩评论