How can I access enum atributes in HQL?
I have an Enum like this:
TicketPriority {
LOW(4),
NORMAL(3),
HIGH(2),
IMMEDIATE(1);
private Integer index;
TicketPriority (Integer index){
this.index = index;
}
public Integer getIndex(){
return this.index;
}
public void setIndex(Integer index){
this.index = index;
}
}
... and I have an Ticket entity that has a priority. The problem: I need t开发者_StackOverflow中文版o order my results by priority so I thought that this would work, but it didn't:
select t from Ticket t order by t.priority.index
I got an error from Hibernate. Any idea besides create Priority as an entity?
Thanks for any suggestion! :)
You cannot do it this way.
HQL query is converted to SQL for execution, therefore all properties referenced in HQL query should be stored in the database. Since your index
property is not stored in the database, HQL query with it can't be converted to SQL query.
You can use enums in ORDER BY
clause of HQL query only to sort by the natural order of their database representation (i.e. names or ordinal numbers).
You have several options:
Organize your
enum
s so that order of their declarations matches the desired order of theirindex
es and configure Hibernate to store them in the database as ordinal numbers. If it's already configured, in your case the desired query would beselect t from Ticket t order by t.priority desc
Use
@Embeddable
/<component>
class instead ofenum
to storeindex
in the database.- Write a custom type to represent your enum as
index
.
精彩评论